Improve solution for problem 47

This commit is contained in:
2019-09-28 11:31:06 +02:00
parent ed7031df4d
commit 7489196be8
2 changed files with 64 additions and 90 deletions

View File

@ -15,88 +15,81 @@
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include "projecteuler.h"
#define N 150000
int count_distinct_factors(int n);
int *primes;
int *count_factors(int n);
int main(int argc, char **argv)
{
int i, found = 0;
int i, count, res;
int *factors;
double elapsed;
struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start);
if((primes = sieve(N)) == NULL)
if((factors = count_factors(N)) == NULL)
{
fprintf(stderr, "Error! Sieve function returned NULL\n");
fprintf(stderr, "Error! Count_factors function returned NULL\n");
return 1;
}
/* Starting from 647, count the distinct prime factors of n, n+1, n+2 and n+3.
* If they all have 4, the solution is found.*/
for(i = 647; !found && i < N - 3; i++)
{
if(!primes[i] && !primes[i+1] && !primes[i+2] && !primes[i+3])
{
if(count_distinct_factors(i) == 4 && count_distinct_factors(i+1) == 4 &&
count_distinct_factors(i+2) == 4 && count_distinct_factors(i+3) == 4)
{
found = 1;
}
}
}
count = 0;
free(primes);
for(i = 0; i < N; i++)
{
if(factors[i] == 4)
{
count++;
}
else
{
count = 0;
}
if(count == 4)
{
res = i - 3;
break;
}
}
clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 47\n");
printf("Answer: %d\n", i-1);
printf("Answer: %d\n", res);
printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0;
}
int count_distinct_factors(int n)
/* Function using a modified sieve of Eratosthenes to count
* the distinct prime factors of each number.*/
int *count_factors(int n)
{
int i, count=0;
int i = 2, j;
int *factors;
/* Start checking if 2 is a prime factor of n. Then remove
* all 2s factore.*/
if(n % 2 == 0)
if((factors = (int *)calloc(n, sizeof(int))) == NULL)
{
count++;
do
{
n /= 2;
}while(n % 2 == 0);
return NULL;
}
/* Check all odd numbers i, if they're prime and they're a factor
* of n, count them and then divide n for by i until all factors i
* are eliminated. Stop the loop when n=1, i.e. all factors have
* been found.*/
for(i = 3; n > 1; i += 2)
while(i < n / 2)
{
if(primes[i] && n % i == 0)
if(factors[i] == 0)
{
count++;
do
for(j = i; j < n; j += i)
{
n /= i;
}while(n % i == 0);
factors[j]++;
}
}
i++;
}
return count;
return factors;
}