Search

Categories

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Send mail to the author(s) E-mail

# Thursday, December 30, 2010
( Euler )

Work out the first ten digits of the sum of the following one-hundred 50-digit numbers. (see project Euler!)

http://www.csharp-station.com/Tutorials/Lesson02.aspx

Type Size (in bits) Range
sbyte 8 -128 to 127
byte 8 0 to 255
short 16 -32768 to 32767
ushort 16 0 to 65535
int 32 -2147483648 to 2147483647
uint 32 0 to 4294967295
long 64 -9223372036854775808 to 9223372036854775807
ulong 64 0 to 18446744073709551615
char 16 0 to 65535

or in .NET4 System.Numerics.BigInteger.. remember to add the reference first, then put in the using statement.

My first try was using BigInteger :-)

[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
string csvStringOfNumbers = "37107287533902102798797998220837590246510135740250," +
"46376937677490009712648124896970078050417018260538," +
string[] numbers = csvStringOfNumbers.Split(',');
BigInteger number = 0;
BigInteger sum = 0;
for (int i = 0; i < 100; i++)
{
number = BigInteger.Parse(numbers[i]);
sum += number;
}

string sumAsString = sum.ToString();
string firstTen = sumAsString.Substring(0, 10);

Assert.AreEqual(1, firstTen);
}
Comments [0] | | # 
# Wednesday, December 29, 2010
( Euler )

The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be:

1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...

Finding ‘Triangle numbers’ can be done by either:

[TestMethod]
public void Get6thTriangenumber()
{
int result = GetTriangleNumber(6);
Assert.AreEqual(21, result);
}

[TestMethod]
public void Get7thTriangenumber()
{
int result = GetTriangleNumber(7);
Assert.AreEqual(28, result);
}

 

public int GetTriangleNumber(int nThNumberInTriangleSequence)
{
int sumOfNumbers = 0;
for (int i = 1; i <= nThNumberInTriangleSequence; i++)
sumOfNumbers += i;

return sumOfNumbers;
}

or we could use the summation formula (faster).. this sums up n numbers in a sequence eg 1,2,3,4,5,6 (see first test above)

public int GetTriangleNumber(int nThNumberInTriangleSequence)
{
int sumOfNumbers = nThNumberInTriangleSequence * (nThNumberInTriangleSequence + 1) / 2;
return sumOfNumbers+1;
}

Factorising – What integers will it divide by with no remainder?

Let us list the factors of the first seven triangle numbers:

1: 1
3: 1,3
6: 1,2,3,6
10: 1,2,5,10
15: 1,3,5,15
21: 1,3,7,21
28: 1,2,4,7,14,28

We can see that 28 is the first triangle number to have over five divisors.

What is the value of the first triangle number to have over five hundred divisors?

http://www.mathsisfun.com/numbers/factors-all-tool.html

[TestMethod]
public void GetFactorCount36() // an exact square
{
int result = GetFactorCount(36);
Assert.AreEqual(9, result);
}

[TestMethod]
public void GetFactorCount45()
{
int result = GetFactorCount(45);
Assert.AreEqual(6, result);
}

[TestMethod]
public void GetFactorCount55()
{
int result = GetFactorCount(55);
Assert.AreEqual(4, result);
}

[TestMethod]
public void GetFactorCount30() // this isn't triangular
{
int result = GetFactorCount(30);
Assert.AreEqual(8, result);
}

Really Simple Factorisation to Get How Many Factors
public int GetFactorCount(int numberToCheck)
{
// we know 1 is a factor and the numberToCheck
int factorCount = 2;
// start from 2 as we know 1 is a factor, and less than as numberToCheck is a factor
for (int i = 2; i < numberToCheck; i++)
{
if (numberToCheck % i == 0)
factorCount++;
}
return factorCount;
}

However this isn’t fast enough.
Factorisation using Square Root

find square root of the number eg for 30 it is 5.477.  Then find all factors below that sqrt, then double.  if number is an exact square then add one.

eg 30

1*30 = 30
2*15 = 30
3*10 = 30
5*6 = 30
sqrt of 30 = 5.477
6*5 = 30
10*3 = 30
15*2 = 30
30*1 = 30

 
public int GetFactorCount(int numberToCheck)
{
int factorCount = 0;
int sqrt = (int)Math.Ceiling(Math.Sqrt(numberToCheck));

// Start from 1 as we want our method to also work when numberToCheck is 0 or 1.
for (int i = 1; i < sqrt; i++)
{
if (numberToCheck % i == 0)
factorCount += 2; // We found a pair of factors.
}

// Check if our number is an exact square.
if (sqrt * sqrt == numberToCheck)
factorCount++;

return factorCount;
}

 

Comments [0] | | # 
# Monday, December 27, 2010
( Euler )

The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.

Find the sum of all the primes below two million.

Here is code which didn’t work as I’d used int’s instead of longs:

[TestClass]
public class UnitTest1
{
[TestMethod]
public void CalculateTheSumOfPrimesBelow10()
{
long result = PrimeTester.calculateTheSumOfPrimesBelow(10);
Assert.AreEqual(17, result);
}

[TestMethod]
public void CalculateTheSumOfPrimesBelow20()
{
long result = PrimeTester.calculateTheSumOfPrimesBelow(20);
Assert.AreEqual(77, result);
}


[TestMethod]
public void CalculateTheSumOfPrimesBelow2million()
{
int result = PrimeTester.calculateTheSumOfPrimesBelow(2000000); // 2million
Assert.AreEqual(1179908154, result); // 1,179,908,154 .. this was what I got with an int...
// correct answer was 142,913,828,922 with a long
}
}


public static class PrimeTester
{
public static int calculateTheSumOfPrimesBelow(int maxPrimeBelow)
{
// we know 2 is a prime number
int sumOfPrimes = 2;
int currentNumberBeingTested = 3;
while (currentNumberBeingTested < maxPrimeBelow)
{
double squareRootOfNumberBeingTested = (double)Math.Sqrt(currentNumberBeingTested);

bool isPrime = true;
for (int i = 2; i <= squareRootOfNumberBeingTested; i++)
{
if (currentNumberBeingTested % i == 0)
{
isPrime = false;
break;
}
}

if (isPrime)
sumOfPrimes += currentNumberBeingTested;

currentNumberBeingTested += 2; // as we don't want to test even numbers
}
return sumOfPrimes;
}
}

and here is the working version with the checked keyword:


[TestMethod]
public void CalculateTheSumOfPrimesBelow2million()
{
long result = PrimeTester.calculateTheSumOfPrimesBelow(2000000); // 2million
Assert.AreEqual(1179908154, result); // 1,179,908,154 .. this was what I got with an int...
// correct answer was 142,913,828,922 with a long
}
}


public static class PrimeTester
{
public static long calculateTheSumOfPrimesBelow(int maxPrimeBelow)
{
// we know 2 is a prime number
int sumOfPrimes = 2;
int currentNumberBeingTested = 3;
while (currentNumberBeingTested < maxPrimeBelow)
{
double squareRootOfNumberBeingTested = (double)Math.Sqrt(currentNumberBeingTested);

bool isPrime = true;
for (int i = 2; i <= squareRootOfNumberBeingTested; i++)
{
if (currentNumberBeingTested % i == 0)
{
isPrime = false;
break;
}
}

checked
{
if (isPrime)
sumOfPrimes += currentNumberBeingTested;
}

currentNumberBeingTested += 2; // as we don't want to test even numbers
}
return sumOfPrimes;
}
}
 
or we can use a compiler option tick for check for arithmetic overflow/underflow.
screen

Comments [0] | | # 
( Euler )

Attacked this using TDD one step at a time:

[TestMethod]
public void GetRow1Col2ShouldBe99()
{
int result = ArrayTester.GetData(1, 2);
Assert.AreEqual(99, result);
}

[TestMethod]
public void GetHorizontalProductOfFirstFourNumbersInRow0()
{
int resultingProduct = 0;
for (int i = 0; i <= 3; i++)
{
if (i == 0)
resultingProduct = ArrayTester.GetData(0, 0);
else
resultingProduct = resultingProduct * ArrayTester.GetData(0, i);
}

Assert.AreEqual(34144, resultingProduct);
}

[TestMethod]
public void FindMaxHorizonatalProductsInRow0()
{
int result = ArrayTester.FindMaxHorizonalProductInRow(0);
Assert.AreEqual(4204200, result);
}

and code:

public static int FindMaxHorizonalProductInRow(int row)
{
List<int> listOfProducts = new List<int>();
for (int startingPosition = 0; startingPosition <= 16; startingPosition++) // as we know it will finish at 19
{
int resultingProduct = 0;
for (int j = 0; j <= 3; j++)
{
if (j == 0)
resultingProduct = ArrayTester.GetData(row, startingPosition);
else
resultingProduct = resultingProduct * ArrayTester.GetData(row, startingPosition + j);
}
listOfProducts.Add(resultingProduct);
}
return listOfProducts.Max();
}

public static int GetData(int row, int col)
{
int[,] numberArray = { { 08, 02, 22, 97, 38, 15, 00, 40, 00, 75, 04, 05, 07, 78, 52, 12, 50, 77, 91, 08 },
{49, 49, 99, 40, 17, 81, 18, 57, 60, 87, 17, 40, 98, 43, 69, 48, 04, 56, 62, 00},
{81, 49, 31, 73, 55, 79, 14, 29, 93, 71, 40, 67, 53, 88, 30, 03, 49, 13, 36, 65 },
{52, 70, 95, 23, 04, 60, 11, 42, 69, 24, 68, 56, 01, 32, 56, 71, 37, 02, 36, 91},
{22, 31, 16, 71, 51, 67, 63, 89, 41, 92, 36, 54, 22, 40, 40, 28, 66, 33, 13, 80},
{24, 47, 32, 60, 99, 03, 45, 02, 44, 75, 33, 53, 78, 36, 84, 20, 35, 17, 12, 50},
{32, 98, 81, 28, 64, 23, 67, 10, 26, 38, 40, 67, 59, 54, 70, 66, 18, 38, 64, 70},
{67, 26, 20, 68, 02, 62, 12, 20, 95, 63, 94, 39, 63, 08, 40, 91, 66, 49, 94, 21},
{24, 55, 58, 05, 66, 73, 99, 26, 97, 17, 78, 78, 96, 83, 14, 88, 34, 89, 63, 72},
{21, 36, 23, 09, 75, 00, 76, 44, 20, 45, 35, 14, 00, 61, 33, 97, 34, 31, 33, 95},
{78, 17, 53, 28, 22, 75, 31, 67, 15, 94, 03, 80, 04, 62, 16, 14, 09, 53, 56, 92},
{16, 39, 05, 42, 96, 35, 31, 47, 55, 58, 88, 24, 00, 17, 54, 24, 36, 29, 85, 57},
{86, 56, 00, 48, 35, 71, 89, 07, 05, 44, 44, 37, 44, 60, 21, 58, 51, 54, 17, 58},
{19, 80, 81, 68, 05, 94, 47, 69, 28, 73, 92, 13, 86, 52, 17, 77, 04, 89, 55, 40},
{04, 52, 08, 83, 97, 35, 99, 16, 07, 97, 57, 32, 16, 26, 26, 79, 33, 27, 98, 66},
{88, 36, 68, 87, 57, 62, 20, 72, 03, 46, 33, 67, 46, 55, 12, 32, 63, 93, 53, 69},
{04, 42, 16, 73, 38, 25, 39, 11, 24, 94, 72, 18, 08, 46, 29, 32, 40, 62, 76, 36},
{20, 69, 36, 41, 72, 30, 23, 88, 34, 62, 99, 69, 82, 67, 59, 85, 74, 04, 36, 16},
{20, 73, 35, 29, 78, 31, 90, 01, 74, 31, 49, 71, 48, 86, 81, 16, 23, 57, 05, 54},
{01, 70, 54, 71, 83, 51, 54, 69, 16, 92, 33, 48, 61, 43, 52, 01, 89, 19, 67, 48}
};
int result = numberArray[row, col];
return result;
}

then just build out the solution using:

horizontal checking

vertical checking

diagonalDown checking

diagonalUp checking

Comments [0] | | # 
# Friday, December 17, 2010
( Euler )

Unit testing paying dividends now.. this was my first try, and importantly I got the answer right first time.  This is what is good about TDD.  Refactoring (which this code needs!) comes later.

A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,

a2 + b2 = c2

For example, 32 + 42 = 9 + 16 = 25 = 52.

There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.

 

[TestClass]
public class UnitTest1
{
[TestMethod]
public void maxValueOf5()
{
pythag pythag = new pythag();
List<string> listOfStrings = pythag.findAllPythagorasTripletsUnder(5);
Assert.IsNotNull(listOfStrings);
}

[TestMethod]
public void passInAStringOfNumbersAndGetBackProduct()
{
pythag pythag = new pythag();
List<string> listOfStrings = new List<string>();
listOfStrings.Add("5,4,3");
int result = pythag.doNumberCrunch(listOfStrings);
Assert.AreEqual(60, result);
}

[TestMethod]
public void mainRun()
{
pythag pythag = new pythag();
List<string> listOfStrings = pythag.findAllPythagorasTripletsUnder(600);
int result = pythag.doNumberCrunch(listOfStrings);
Assert.AreEqual(123, result); // 31875000
}

}

public class pythag
{
public List<string> findAllPythagorasTripletsUnder(int maxValueOfHypotenuse)
{
List<string> listOfString = new List<string>();
for (int c = 1; c <= maxValueOfHypotenuse; c++)
{
for (int b = 1; b <= maxValueOfHypotenuse; b++)
{
for (int a = 1; a <= maxValueOfHypotenuse; a++)
{
if (Math.Pow(a,2) == Math.Pow(b,2) + Math.Pow(c,2))
listOfString.Add(a.ToString() + "," + b.ToString() + "," + c.ToString());
}
}
}
return listOfString;
}

public int doNumberCrunch(List<string> listOfStrings)
{
int product = 0;
foreach (string item in listOfStrings)
{
string[] numbers = item.Split(',');
int a = Convert.ToInt32(numbers[0]);
int b = Convert.ToInt32(numbers[1]);
int c = Convert.ToInt32(numbers[2]);

if (a + b + c == 1000)
product = a * b * c;
}
return product;
}
}

And Phils (and I’ve made it fit into testing runner).   Goto.. but it works and is simple to read!

[TestMethod]
public void testPhilsWayByCheckingAnswerIsCorrect()
{
philsWay philsWay = new philsWay();
double result = philsWay.solveProblem();
Assert.AreEqual(31875000, result); // 31875000 is correct
}

}

public class philsWay
{
public double solveProblem()
{
double answer = 0;
for (int a = 1; a < 100000; a++)
{
for (int b = a; b < 100000; b++)
{

double c = Math.Sqrt((a * a) + (b * b));
if (a + b + c == 1000)
{
Console.WriteLine(a + "," + b + "," + c);
answer = a * b * c;
goto Foo;
}
}
}

Foo:
return answer;
}
}

and here is refactored version of my code:

public List<string> findAllPythagorasTripletsUnder(int maxValueOfHypotenuse)
{
List<string> listOfString = new List<string>();
for (int a = 1; a <= maxValueOfHypotenuse; a++)
{
for (int b = 1; b <= maxValueOfHypotenuse; b++)
{
int c = Convert.ToInt32(Math.Sqrt((a * a) + (b * b))); // converting to int to avoid getting positive double results
if (Math.Pow(c, 2) == Math.Pow(a, 2) + Math.Pow(b, 2))
listOfString.Add(a.ToString() + "," + b.ToString() + "," + c.ToString());
}
}
return listOfString;
}

Comments [1] | | # 
# Thursday, December 16, 2010
( Euler )

Find the largest Product.. I got product wrong initially.  I summed instead.  Unit testing was great as when I realised my mistake was an easy fix, and had confidence in the code.

 

[TestClass]
public class UnitTest1
{
[TestMethod]
public void findGreatestProductOf5ConsecutiveDigitsInSimpleString()
{
string stringOfNumbers = "1111112341111";
ProductFinder productFinder = new ProductFinder();
int result = productFinder.findGreatestProduct(stringOfNumbers);
Assert.AreEqual(11, result);

}

[TestMethod]
public void findGreatestProductOf5ConsecutiveDigitsInLongString()
{
string stringOfNumbers = "731671765313306249192251196744265747423553...";
ProductFinder productFinder = new ProductFinder();
int result = productFinder.findGreatestProduct(stringOfNumbers);
Assert.AreEqual(123, result);
}
}

public class ProductFinder
{
public int findGreatestProduct(string stringOfNumbers)
{
//try first 3
int lengthOfString = stringOfNumbers.Count();
List<int> listOfResults = new List<int>();

char[] numbers = stringOfNumbers.ToArray();
for (int i = 0; i < lengthOfString-6; i++)
{
int first = Convert.ToInt32(stringOfNumbers.Substring(i, 1));
int second = Convert.ToInt32(stringOfNumbers.Substring(i+1, 1));
int third = Convert.ToInt32(stringOfNumbers.Substring(i+2, 1));
int fourth = Convert.ToInt32(stringOfNumbers.Substring(i+3, 1));
int fifth = Convert.ToInt32(stringOfNumbers.Substring(i+4, 1));

int result = first * second * third * fourth * fifth;
listOfResults.Add(result);
}

int largestProduct = listOfResults.Max();
return largestProduct;
}
}

Comments [0] | | # 
( Euler )

Find the 10001th Prime

I used the test runner here to give me the answer.. didn’t even use a console application.

[TestClass]
public class UnitTest1
{
[TestMethod]
public void getSixthPrime()
{
PrimeTester primeTester = new PrimeTester();
int result = primeTester.generateThisNumberOfPrimes(6);
Assert.AreEqual(13, result);
}

[TestMethod]
public void getSeventhPrime()
{
PrimeTester primeTester = new PrimeTester();
int result = primeTester.generateThisNumberOfPrimes(7);
Assert.AreEqual(17, result);
}

[TestMethod]
public void getAnswerPrime() //10001
{
PrimeTester primeTester = new PrimeTester();
int result = primeTester.generateThisNumberOfPrimes(10001);
Assert.AreEqual(12345, result);
}

and the class:
public class PrimeTester
{
public int generateThisNumberOfPrimes(int numberOfPrimesToGenerate)
{
List<int> primes = new List<int>();

int toGenerate = 2147483630; // nearly the largest int.
primes.Add(2);

int currentNumberBeingTested = 3;
while (primes.Count < toGenerate)
{
int squareRootOfNumberBeingTested = (int)Math.Sqrt(currentNumberBeingTested);

bool isPrime = true;
for (int i = 0; i < primes.Count && (primes[i] <= squareRootOfNumberBeingTested); ++i)
{
if (currentNumberBeingTested % primes[i] == 0)
{
isPrime = false;
break;
}
}

if (isPrime)
primes.Add(currentNumberBeingTested);

if (primes.Count == numberOfPrimesToGenerate)
break;

currentNumberBeingTested += 2; // as we don't want to test even numbers
}
return primes[primes.Count-1];
}
}

Comments [0] | | # 
( Euler | TDD | VS2010 )

I decided to try and do Test Driven Development here, so avoid any small problems.

Problem was that my test harness in VS2010 wouldn’t start the agent: http://stackoverflow.com/questions/4446416/vs2010-test-runner-unable-to-start-agent-process (Edit: It was Avira AntiVirus that was the culprit)

alt text

After reinstalling VS2010, and trying to remember all the changes I’ve made since it last worked.. I can run all the tests, just not in the debugger.  Which is very useful.

Euler problem is interesting:

The sum of the squares of the first ten natural numbers is,

12 + 22 + ... + 102 = 385

The square of the sum of the first ten natural numbers is,

(1 + 2 + ... + 10)2 = 552 = 3025

Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640.

Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.

Source code here:    

 

class Program
{
static void Main(string[] args)
{
stuff thing = new stuff();
double sumOfSqaures = thing.sumOfSquares(100);
double sqaureOfSums = thing.SquareOfSum(100);
double result = sqaureOfSums - sumOfSqaures;
Console.WriteLine(result);
}
}

public class stuff
{
public double sumOfSquares(double upToInt)
{
double total = 0;
for (int i = 1; i <= upToInt; i++)
total += Math.Pow(i, 2);

return total;
}

public double SquareOfSum(int upToInt)
{
double sum = 0;
for (int i = 0; i <= upToInt; i++)
sum += i;

return Math.Pow(sum, 2);
}
}

and test code:

[TestClass]
public class UnitTest1
{
[TestMethod]
public void SumOfSquaresOfFirst10()
{
stuff thing = new stuff();
double result = thing.sumOfSquares(10);
Assert.AreEqual(385, result);
}

[TestMethod]
public void SquareOfSumOfFirst10()
{
stuff thing = new stuff();
double result = thing.SquareOfSum(10);
Assert.AreEqual(3025, result);
}

[TestMethod]
public void DifferenceBetweenTwoAbove()
{
stuff thing = new stuff();
double sumOfSqaures = thing.sumOfSquares(10);
double sqaureOfSums = thing.SquareOfSum(10);
double result = sqaureOfSums - sumOfSqaures;
Assert.AreEqual(2640, result);
}

}

It was great using TDD.. made it very easy, and got answer right first time!

Comments [0] | | # 
# Monday, December 13, 2010
( Euler )

2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.

What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?

Or ‘Exactly Divisible’

int numberToTest = 1;
while (1 == 1)
{
bool divisible = true;
for (int j = 1; j <= 20; j++)
{
if (numberToTest % j != 0)
{
divisible = false;
break;
}
}
if (divisible)
break;
numberToTest++;
}

for (int i = 1; i <= 20; i++)
Console.WriteLine(i + " " + numberToTest / i);

Console.WriteLine(numberToTest); // 232 792 560

This took me a while with an elementary programming mistake.. corrected and got it.  I will try and build in more testing into the following problems to avoid simple errors.
Comments [0] | | # 
# Sunday, December 12, 2010
( Euler )

A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.

Find the largest palindrome made from the product of two 3-digit numbers.

static void Main(string[] args)
{
IList<int> listOfPalindromes = new List<int>();
for (int i = 100; i <= 999; i++)
{
for (int j = 100; j <= 999; j++)
{
int product = i * j;
if (product >= 100000)
{
string productAsString = Convert.ToString(product);
if ((productAsString[0] == productAsString[5]) && (productAsString[1] == productAsString[4]) && (productAsString[2] == productAsString[3]))
listOfPalindromes.Add(product);
}
}
}

foreach (var number in listOfPalindromes.OrderBy(x => x))
Console.WriteLine(number.ToString());
}

906609

Phils way:

static void Main(string[] args)
{
int max = 0;

for (int a = 999; a > 2; a--)
{
for (int b = 999; b > 2; b--)
{

string ans = Convert.ToString(a * b);
int counter = 0;
for (int x = 0; x < ans.Length; x++)
{
if (ans[x] == ans[ans.Length - x-1])
{
counter++;
}
}

if (counter == ans.Length && Convert.ToInt32(ans)>max)
{
max = Convert.ToInt32(ans);

}
}
}

Console.WriteLine(max);
Console.ReadLine();

Comments [0] | | # 
( Euler )

The prime factors of 13195 are 5, 7, 13 and 29.

What is the largest prime factor of the number 600851475143 ?

The secret here is that you only need to test prime numbers up to the square root of 600billion number above.

Why?

     
18 * 2 36
17    
16    
15    
14    
13    
12 * 3 36
11    
10    
9 * 4 36
8    
7    
6 * 6 36
5   36
4 * 9 36
3 * 12 36
2 * 18 36

Go above 6, and 9 * 4 is the same as 4 * 9… same for 12 * 3, 18 * 2.

So we need only find all the primes up to (int)Math.Sqrt(numberToGetLargestPrimeFactorOf); // 775146

Then see which is the largest which divides by the 600billion number

which is: 6857  (divides it as: 87,625,999)

There are no larger primes which are divisible by the 600 billion number.

// What is the largest prime factor of the number 600851475143 ? 600,851,475,143
// we only need to check prime numbers up to Sqrt(600851475143)
static void Main(string[] args)
{
long numberToGetLargestPrimeFactorOf = 600851475143;
int squareRootOfnumberToGetLargestPrimeFactorOf = (int)Math.Sqrt(numberToGetLargestPrimeFactorOf); // 775146

List<int> listOfPrimes = generatePrimes(775146);
List<int> listOfPrimeFactors = new List<int>();
for (int i = listOfPrimes.Count-1; i > 0; i--)
{
int intToDivideBy = listOfPrimes[i];
if (numberToGetLargestPrimeFactorOf % intToDivideBy == 0)
{
listOfPrimeFactors.Add(intToDivideBy);
Console.WriteLine("factor is " + intToDivideBy.ToString());
}
}
}

public static List<int> generatePrimes(int toGenerate)
{
List<int> primes = new List<int>();

if (toGenerate > 0) primes.Add(2);

int curTest = 3;
while (primes.Count < toGenerate)
{
int sqrt = (int)Math.Sqrt(curTest);

bool isPrime = true;
for (int i = 0; i < primes.Count && (primes[i] <= sqrt); ++i)
{
if (curTest % primes[i] == 0)
{
isPrime = false;
break;
}
}

if (isPrime)
primes.Add(curTest);
curTest += 2;
}
return primes;
}

Some other code which was much less efficient, but more readable in my opinion was:

IEnumerable<int> listOfInts = Enumerable.Range(2, 775146).Where(i => (i % 2 != 0));
IList<int> listOfPrimes = new List<int>();

foreach (int intToCheck in listOfInts)
{
bool isPrime = true;
// divide the intToCheck against all numbers in the list lower than it
foreach (int intToDivideBy in listOfInts)
{
if (intToCheck != intToDivideBy)
{
if ((intToCheck % intToDivideBy) == 0)
isPrime = false;
}
}
if (isPrime)
listOfPrimes.Add(intToCheck);
}

foreach (int intToDivideBy in listOfPrimes.Reverse())
{
if (numberToGetLargestPrimeFactorOf % intToDivideBy == 0)
{
listOfPrimeFactors.Add(intToDivideBy);
break; // stop processing as found the highest
}
}

Comments [0] | | # 
# Wednesday, December 08, 2010
( Euler )
//Find the sum of all the even-valued terms in the sequence which do not exceed four million.
static void Main(string[] args)
{
List<int> fibList = new List<int>();
fibList.Add(1); // index 0
fibList.Add(2); // index 1

int i = 2;
while (fibList[fibList.Count-1] < 4000000)
{
int secondLastValue = fibList[i - 2];
int lastValue = fibList[i - 1];
int valueToAdd = secondLastValue + lastValue;
fibList.Add(valueToAdd);
i++;
}

fibList.RemoveAt(fibList.Count - 1); // remove last item in list as it will be over the 4,000,000 limit

// get even values
List<int> fibListEven = new List<int>();
foreach (int intToTry in fibList)
{
if (intToTry % 2 == 0)
fibListEven.Add(intToTry);
}

int sumOfEvens = 0;
foreach (int intToDisplay in fibListEven)
sumOfEvens += intToDisplay;

Console.WriteLine(sumOfEvens.ToString());
Console.ReadLine(); // should be 4613732
}

Found this on http://stackoverflow.com/questions/1580985/finding-fibonacci-sequence-in-c-project-euler-exercise
 
[TestMethod]
public void TestMethod1()
{
long result = 0;

foreach (int i in Fibonacci().TakeWhile(i => i < 4000000).Where(j => j % 2 == 0))
result += i;

Assert.AreEqual(1, result); // 4,613,732
}

public IEnumerable<int> Fibonacci()
{
int n1 = 0;
int n2 = 1;

yield return 1;
while (true)
{
int n = n1 + n2;
n1 = n2;
n2 = n;
yield return n;
}
}

Comments [0] | | # 
( c# language | Euler | Linq )

This is a fun site:

http://projecteuler.net

The first problem is:

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

Find the sum of all the multiples of 3 or 5 below 1000.

static void Main(string[] args)
{
int overallSum = 0;
for (int i = 1; i < 1000; i++)
{
if ((i % 3 == 0) || (i % 5 == 0))
overallSum += i;
}
Console.WriteLine("overall sum is: " + overallSum.ToString());
Console.ReadLine();
}
// should be 233168

or Phils way:

//Find the sum of all the multiples of 3 or 5 below 1000.
//There is a summation formula which states
//The sum of all numbers from i = 1 to i = n is n(n+1)/2
static void Main(string[] args)
{
int total = (3 * Convert.ToInt32(999 / 3) * (Convert.ToInt32((999 / 3)) + 1)) / 2
+ (5 * Convert.ToInt32(999 / 5) * (Convert.ToInt32((999 / 5)) + 1)) / 2
- (15 * Convert.ToInt32(999 / 15) * (Convert.ToInt32((999 / 15)) + 1)) / 2;

Console.WriteLine("overall sum is: " + total.ToString());
Console.ReadLine();

}

from http://answers.yahoo.com/question/index?qid=20100422031504AAfmpJ5)

or Simons way using method syntax (or fluent)

int result = Enumerable.Range(0, 1000)  // generates a sequence of numbers in a range
.Where(i => i % 3 == 0 || i % 5 == 0) // filter using lambda expression
.Sum(); // sum of int32 using extension methods


and for fun, using method and query syntax
 
// get the ones divisible by 3 in the list - Method syntax
IEnumerable<int> listOfDivisibleBy3Method = listOfInts
.Where(i => i % 3 == 0);

// get the ones divisible by 3 in the list - Query syntax
IEnumerable<int> listOfDivisibleBy3Query = from number in listOfInts
where (number % 3 == 0)
select number;

http://stackoverflow.com/questions/214500/which-linq-syntax-do-you-prefer-fluent-or-query-expression

Comments [0] | | #