ProjectEuler.net is a fun website which posts computational problems. I’ve chosen several easy ones to solve using C#.
Problem 2
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
int fibNum = 0; int prevNum = 1; int sum = 0; while (true) { int temp = fibNum; fibNum = prevNum; prevNum = temp + prevNum; if (fibNum > 4000000) break; if (fibNum % 2 == 0) { sum += fibNum; } } Console.WriteLine("SUM : " + sum); |
Problem 5
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
bool bDivisibleby10 = false; int currentNum = 0; while (true) { currentNum++; for (int i = 1; i <= 20; i++) { if ((currentNum % i) == 0) { bDivisibleby10 = true; } else { bDivisibleby10 = false; break; } } if (bDivisibleby10) { Console.WriteLine("Answer : " +currentNum); break; } } |
Problem 6
Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
int sum_of_squares = 0; for (int i = 1; i <= 100; i++) { sum_of_squares += (int)Math.Pow(i, 2); } int square_of_sum = 0; for (int i = 1; i <= 100; i++) { square_of_sum += i; } Console.WriteLine("Difference : " + ( Math.Pow(square_of_sum, 2) - sum_of_squares)); |
Problem 7
What is the 10,001st prime number?
static void Main(string[] args) { int currentPrime = 1; int primeNum = 0; while (true) { if (isPrime(currentPrime)) primeNum++; if (primeNum == 10001) break; currentPrime++; } Console.WriteLine( currentPrime ); } public static bool isPrime(int n) { if (n == 1) return false; if (n == 2) return true; for (int i = 2; i < n; ++i) { if ((n % i) == 0) return false; } return true; } |