wow that was hard. Thanks 'http://stackoverflow.com/questions/1988782…

`…/why-do-i-fail-project-euler-10' for the 'long long' tip`
1 parent c3e976c commit 44ef2145a354813be14ab86845e1338305e93bf6 committed Oct 13, 2010
Showing with 95 additions and 0 deletions.
1. +44 −0 10/solution (attempt 1).c
2. +48 −0 10/solution.c
3. +2 −0 10/solution.rb
4. +1 −0 generate.rb
 @@ -0,0 +1,44 @@ +// Solving Project Euler Problem #10 +#include +#include +#include +#include +using namespace std; + +int is_prime(int * n, int arr[]) { + bool prime = true; + int max_index = arr[0]; + for (int i=1; i <= max_index; i+=1) { + prime = (*n % arr[i] != 0); + if (!prime) + return (false); + // A prime number will not have any factors that are greater than half of itself. + if (arr[i] > (*n / 2)){ + return (true); + } + } + return (true); +} + +int main (int argc, char *argv[]) +{ + long long total = 10; + // arr[0] keeps track of the array size. + // (arr is seeded with the first 3 primes.) + int arr[2000001] = {3, 2, 3, 5}; + + for (int n=7; n < 2000000; n+=2){ + if (is_prime (&n, arr)) { + arr[0] += 1; + arr[arr[0]] = n; + total += n; + } + if ((n-1) % 1000 == 0) + cout << "\r" << n; + } + + cout << "\r== Total: " << total << "\n\n"; + + return 0; +} +
 @@ -0,0 +1,48 @@ +// Solving Project Euler Problem #10 +#include +#include +#include +#include +#include +using namespace std; + +int is_prime(int * n) { + // Not divisible by 2 or 3 + if (*n % 3 == 0) + return (false); + + // No prime number has factors greater than the sqrt of itself. + int max = int (sqrt ((double)*n)); + + for (int i=3; i <= max; i+=2) { + if (*n % i == 0) + return(false); + } + return(true); +} + +int main (int argc, char *argv[]) +{ + long long max; + if (argc == 2){ + max = atoi(argv[1]); + } else { + max = 2000000LL; + } + + cout << "=== Summing all primes up to: " << max << "\n\n"; + + long long total = 2 + 3; + for (int n = 5; n < max; n += 2){ + if (is_prime (&n)) { + total += n; + } + if ((n - 1) % 1000 == 0) + cout << "\r" << n; + } + + cout << "\r== Total: " << total << "\n\n"; + + return 0; +} +
 @@ -43,3 +43,5 @@ def is_prime?(n) puts "\n\n===== Sum of primes: #{@total}" +# This is rubbish! Way too slow in ruby. +
 @@ -6,4 +6,5 @@ system("mkdir #{ARGV[0]}") system("cp -f template.rb #{ARGV[0]}/solution.rb") +system("cp -f template.c #{ARGV[0]}/solution.c")