solution for problem #3

This commit is contained in:
Colin McMillen 2020-11-17 14:25:33 -05:00
parent d1b166d91d
commit e6a6bd34f6

View File

@ -5,9 +5,9 @@ namespace Euler {
class Program {
static int Problem1() {
int sum = 0;
for (int i = 1; i < 1000; i++) {
static long Problem1() {
long sum = 0;
for (long i = 1; i < 1000; i++) {
if (i % 3 == 0 || i % 5 == 0) {
sum += i;
}
@ -16,18 +16,18 @@ namespace Euler {
}
static long Problem2() {
int max = 4_000_000;
long max = 4_000_000;
var fibs = new List<int>();
var fibs = new List<long>();
fibs.Add(1);
fibs.Add(2);
while (fibs[fibs.Count - 1] < max) {
int num = fibs[fibs.Count - 1] + fibs[fibs.Count - 2];
long num = fibs[fibs.Count - 1] + fibs[fibs.Count - 2];
fibs.Add(num);
}
int sum = 0;
long sum = 0;
foreach (int i in fibs) {
if (i % 2 == 0 && i <= max) {
sum += i;
@ -37,8 +37,41 @@ namespace Euler {
return sum;
}
static bool IsPrime(long num, List<long> primes) {
foreach (long i in primes) {
if (num % i == 0) {
return false;
}
}
return true;
}
static List<long> PrimesUpThrough(long num) {
var primes = new List<long>();
primes.Add(2);
for (int i = 3; i <= num; i += 2) {
if (IsPrime(i, primes)) {
primes.Add(i);
}
}
return primes;
}
static long Problem3() {
long target = 600_851_475_143;
long targetSqrt = (long) Math.Sqrt(target);
List<long> primes = PrimesUpThrough(targetSqrt);
long highestPrimeFactor = 0;
foreach (long i in primes) {
if (target % i == 0) {
highestPrimeFactor = i;
}
}
return highestPrimeFactor;
}
static void Main(string[] args) {
Console.WriteLine(Problem2());
Console.WriteLine(Problem3());
}
}
}