C# solutions to Project Euler problems.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

76 lines
1.5 KiB

  1. using System;
  2. using System.Collections.Generic;
  3. namespace Euler {
  4. class Program {
  5. static long Problem1() {
  6. long sum = 0;
  7. for (long i = 1; i < 1000; i++) {
  8. if (i % 3 == 0 || i % 5 == 0) {
  9. sum += i;
  10. }
  11. }
  12. return sum;
  13. }
  14. static long Problem2() {
  15. long max = 4_000_000;
  16. var fibs = new List<long>();
  17. fibs.Add(1);
  18. fibs.Add(2);
  19. while (fibs[fibs.Count - 1] < max) {
  20. long num = fibs[fibs.Count - 1] + fibs[fibs.Count - 2];
  21. fibs.Add(num);
  22. }
  23. long sum = 0;
  24. foreach (int i in fibs) {
  25. if (i % 2 == 0 && i <= max) {
  26. sum += i;
  27. }
  28. }
  29. return sum;
  30. }
  31. static bool IsPrime(long num, List<long> primes) {
  32. foreach (long i in primes) {
  33. if (num % i == 0) {
  34. return false;
  35. }
  36. }
  37. return true;
  38. }
  39. static List<long> PrimesUpThrough(long num) {
  40. var primes = new List<long>();
  41. primes.Add(2);
  42. for (int i = 3; i <= num; i += 2) {
  43. if (IsPrime(i, primes)) {
  44. primes.Add(i);
  45. }
  46. }
  47. return primes;
  48. }
  49. static long Problem3() {
  50. long target = 600_851_475_143;
  51. long targetSqrt = (long) Math.Sqrt(target);
  52. List<long> primes = PrimesUpThrough(targetSqrt);
  53. long highestPrimeFactor = 0;
  54. foreach (long i in primes) {
  55. if (target % i == 0) {
  56. highestPrimeFactor = i;
  57. }
  58. }
  59. return highestPrimeFactor;
  60. }
  61. static void Main(string[] args) {
  62. Console.WriteLine(Problem3());
  63. }
  64. }
  65. }