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.

115 lines
2.3 KiB

  1. using System;
  2. using System.Collections.Generic;
  3. namespace Euler {
  4. class Program {
  5. static void Debug(long l) {
  6. Console.WriteLine(l);
  7. }
  8. static void Debug(string s) {
  9. Console.WriteLine(s);
  10. }
  11. static void Debug(bool b) {
  12. Console.WriteLine(b);
  13. }
  14. static long Problem1() {
  15. long sum = 0;
  16. for (long i = 1; i < 1000; i++) {
  17. if (i % 3 == 0 || i % 5 == 0) {
  18. sum += i;
  19. }
  20. }
  21. return sum;
  22. }
  23. static long Problem2() {
  24. long max = 4_000_000;
  25. var fibs = new List<long>();
  26. fibs.Add(1);
  27. fibs.Add(2);
  28. while (fibs[fibs.Count - 1] < max) {
  29. long num = fibs[fibs.Count - 1] + fibs[fibs.Count - 2];
  30. fibs.Add(num);
  31. }
  32. long sum = 0;
  33. foreach (int i in fibs) {
  34. if (i % 2 == 0 && i <= max) {
  35. sum += i;
  36. }
  37. }
  38. return sum;
  39. }
  40. static bool IsPrime(long num, List<long> primes) {
  41. foreach (long i in primes) {
  42. if (num % i == 0) {
  43. return false;
  44. }
  45. }
  46. return true;
  47. }
  48. static List<long> PrimesUpThrough(long num) {
  49. var primes = new List<long>();
  50. primes.Add(2);
  51. for (int i = 3; i <= num; i += 2) {
  52. if (IsPrime(i, primes)) {
  53. primes.Add(i);
  54. }
  55. }
  56. return primes;
  57. }
  58. static long Problem3() {
  59. long target = 600_851_475_143;
  60. long targetSqrt = (long) Math.Sqrt(target);
  61. List<long> primes = PrimesUpThrough(targetSqrt);
  62. long highestPrimeFactor = 0;
  63. foreach (long i in primes) {
  64. if (target % i == 0) {
  65. highestPrimeFactor = i;
  66. }
  67. }
  68. return highestPrimeFactor;
  69. }
  70. static bool IsPalindromicNumber(long l) {
  71. string s = "" + l;
  72. for (int i = 0; i < s.Length / 2; i++) {
  73. if (s[i] != s[s.Length - i - 1]) {
  74. return false;
  75. }
  76. }
  77. return true;
  78. }
  79. static long Problem4() {
  80. long largest = 0;
  81. for (long i = 999; i >= 100; i--) {
  82. for (long j = 999; j >= 100; j--) {
  83. long target = i * j;
  84. if (target < largest) {
  85. continue;
  86. }
  87. if (IsPalindromicNumber(target)) {
  88. largest = target;
  89. Debug(largest);
  90. }
  91. }
  92. }
  93. return largest;
  94. }
  95. static void Main(string[] args) {
  96. Debug(Problem4());
  97. }
  98. }
  99. }