Compare commits

..

10 Commits

174 changed files with 7879 additions and 7756 deletions

1
.gitignore vendored
View File

@ -1,2 +1,3 @@
Python/__pycache__ Python/__pycache__
ProblemsOverviews/* ProblemsOverviews/*
Haskell/.stack-work

View File

@ -2,36 +2,38 @@
* *
* Find the sum of all the multiples of 3 or 5 below 1000.*/ * Find the sum of all the multiples of 3 or 5 below 1000.*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <time.h> #include <time.h>
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int i, sum = 0; int i, sum = 0;
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
/* Simple brute-force approach: try every number between 3 and 999, /* Simple brute-force approach: try every number between 3 and 999,
* check if it's a multiple of 3 or 5, if yes add it to the total.*/ * check if it's a multiple of 3 or 5, if yes add it to the total.*/
for(i = 3; i < 1000; i++) for(i = 3; i < 1000; i++)
{ {
if (i % 3 == 0 || i % 5 == 0) if (i % 3 == 0 || i % 5 == 0)
{ {
sum += i; sum += i;
} }
} }
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 1\n"); printf("Project Euler, Problem 1\n");
printf("Answer: %d\n", sum); printf("Answer: %d\n", sum);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0; return 0;
} }

View File

@ -4,6 +4,8 @@
* *
* By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.*/ * By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <time.h> #include <time.h>
@ -12,36 +14,36 @@
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int fib0 = 1, fib1 = 2, fib2, sum = 2; int fib0 = 1, fib1 = 2, fib2, sum = 2;
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
fib2 = fib0 + fib1; fib2 = fib0 + fib1;
/* Simple brute-force approach: generate every value in the Fibonacci /* Simple brute-force approach: generate every value in the Fibonacci
* sequence smaller than 4 million and if it's even add it to the total.*/ * sequence smaller than 4 million and if it's even add it to the total.*/
while(fib2 <= N) while(fib2 <= N)
{ {
if(fib2 % 2 == 0) if(fib2 % 2 == 0)
{ {
sum += fib2; sum += fib2;
} }
fib0 = fib1; fib0 = fib1;
fib1 = fib2; fib1 = fib2;
fib2 = fib0 + fib1; fib2 = fib0 + fib1;
} }
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 2\n"); printf("Project Euler, Problem 2\n");
printf("Answer: %d\n", sum); printf("Answer: %d\n", sum);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0; return 0;
} }

View File

@ -2,6 +2,8 @@
* *
* What is the largest prime factor of the number 600851475143?*/ * What is the largest prime factor of the number 600851475143?*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <time.h> #include <time.h>
@ -11,26 +13,26 @@ long int max_prime_factor(long int num);
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
long int res; long int res;
long int num = 600851475143; long int num = 600851475143;
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
/* Use a function to calculate the largest prime factor.*/ /* Use a function to calculate the largest prime factor.*/
res = max_prime_factor(num); res = max_prime_factor(num);
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 3\n"); printf("Project Euler, Problem 3\n");
printf("Answer: %ld\n", res); printf("Answer: %ld\n", res);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0; return 0;
} }
/* Recursive approach: if num is prime, return num, otherwise /* Recursive approach: if num is prime, return num, otherwise
@ -38,39 +40,39 @@ int main(int argc, char **argv)
* by its prime factors until only the largest remains.*/ * by its prime factors until only the largest remains.*/
long int max_prime_factor(long int num) long int max_prime_factor(long int num)
{ {
long int i; long int i;
/* Use function defined in projecteuler.c to check if a number is prime.*/ /* Use function defined in projecteuler.c to check if a number is prime.*/
if(is_prime(num)) if(is_prime(num))
{ {
return num; return num;
} }
/* If num is even, find the largest prime factor of num/2.*/ /* If num is even, find the largest prime factor of num/2.*/
if(num % 2 == 0) if(num % 2 == 0)
{ {
return max_prime_factor(num/2); return max_prime_factor(num/2);
} }
else else
{ {
i = 3; i = 3;
while(1) while(1)
{ {
/* If num is divisible by i and i is prime, find largest prime /* If num is divisible by i and i is prime, find largest prime
* factor of num/i.*/ * factor of num/i.*/
if(num % i == 0) if(num % i == 0)
{
if(is_prime(i))
{ {
return max_prime_factor(num/i); if(is_prime(i))
{
return max_prime_factor(num/i);
}
} }
}
i += 2; i += 2;
} }
} }
/* Should never get here.*/ /* Should never get here.*/
return -1; return -1;
} }

View File

@ -2,6 +2,8 @@
* *
* Find the largest palindrome made from the product of two 3-digit numbers.*/ * Find the largest palindrome made from the product of two 3-digit numbers.*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <time.h> #include <time.h>
@ -9,36 +11,36 @@
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int i, j, max = 0, num; int i, j, max = 0, num;
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
/* Using a brute-force approach: generate every product of 3-digit numbers /* Using a brute-force approach: generate every product of 3-digit numbers
* and check if it's palindrome. If the product found is greater than the * and check if it's palindrome. If the product found is greater than the
* current maximum, save the current product.*/ * current maximum, save the current product.*/
for(i = 999; i >= 100; i--) for(i = 999; i >= 100; i--)
{ {
for(j = i; j >= 100; j--) for(j = i; j >= 100; j--)
{ {
num = i * j; num = i * j;
/* Use the function defined in projecteuler.c to check if a number is palindrome.*/ /* Use the function defined in projecteuler.c to check if a number is palindrome.*/
if(num > max && is_palindrome(num, 10)) if(num > max && is_palindrome(num, 10))
{ {
max = num; max = num;
} }
} }
} }
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 4\n"); printf("Project Euler, Problem 4\n");
printf("Answer: %d\n", max); printf("Answer: %d\n", max);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0; return 0;
} }

View File

@ -2,6 +2,8 @@
* *
* What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?*/ * What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <time.h> #include <time.h>
@ -9,23 +11,23 @@
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
long int res, n[20] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20}; long int res, n[20] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20};
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
/* Function define in projecteuler.c to find the least common multiple of multiple numbers.*/ /* Function define in projecteuler.c to find the least common multiple of multiple numbers.*/
res = lcmm(n, 20); res = lcmm(n, 20);
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 5\n"); printf("Project Euler, Problem 5\n");
printf("Answer: %ld\n", res); printf("Answer: %ld\n", res);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0; return 0;
} }

View File

@ -10,35 +10,37 @@
* *
* Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.*/ * Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <time.h> #include <time.h>
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int i, sum_squares = 0, square_sum = 0; int i, sum_squares = 0, square_sum = 0;
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
/* Straightforward brute-force approach.*/ /* Straightforward brute-force approach.*/
for(i = 1; i <= 100; i++) for(i = 1; i <= 100; i++)
{ {
sum_squares += i*i; sum_squares += i*i;
square_sum += i; square_sum += i;
} }
square_sum *= square_sum; square_sum *= square_sum;
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 6\n"); printf("Project Euler, Problem 6\n");
printf("Answer: %d\n", square_sum-sum_squares); printf("Answer: %d\n", square_sum-sum_squares);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0; return 0;
} }

View File

@ -2,6 +2,8 @@
* *
* What is the 10 001st prime number?*/ * What is the 10 001st prime number?*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <time.h> #include <time.h>
@ -9,33 +11,33 @@
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int count = 1, n = 1, target = 10001; int count = 1, n = 1, target = 10001;
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
/* Brute force approach: start with count=1 and check every odd number /* Brute force approach: start with count=1 and check every odd number
* (2 is the only even prime), if it's prime increment count, until the * (2 is the only even prime), if it's prime increment count, until the
* target prime is reached.*/ * target prime is reached.*/
while(count != target) while(count != target)
{ {
n += 2; n += 2;
/* Use the function in projecteuler.c to check if a number is prime.*/ /* Use the function in projecteuler.c to check if a number is prime.*/
if(is_prime(n)) if(is_prime(n))
{ {
count++; count++;
} }
} }
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 7\n"); printf("Project Euler, Problem 7\n");
printf("Answer: %d\n", n); printf("Answer: %d\n", n);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0; return 0;
} }

144
C/p008.c
View File

@ -23,90 +23,92 @@
* *
* Find the thirteen adjacent digits in the 1000-digit number that have the greatest product. What is the value of this product?*/ * Find the thirteen adjacent digits in the 1000-digit number that have the greatest product. What is the value of this product?*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <time.h> #include <time.h>
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
char string[] = "73167176531330624919225119674426574742355349" char string[] = "73167176531330624919225119674426574742355349"
"19493496983520312774506326239578318016984801" "19493496983520312774506326239578318016984801"
"86947885184385861560789112949495459501737958" "86947885184385861560789112949495459501737958"
"33195285320880551112540698747158523863050715" "33195285320880551112540698747158523863050715"
"69329096329522744304355766896648950445244523" "69329096329522744304355766896648950445244523"
"16173185640309871112172238311362229893423380" "16173185640309871112172238311362229893423380"
"30813533627661428280644448664523874930358907" "30813533627661428280644448664523874930358907"
"29629049156044077239071381051585930796086670" "29629049156044077239071381051585930796086670"
"17242712188399879790879227492190169972088809" "17242712188399879790879227492190169972088809"
"37766572733300105336788122023542180975125454" "37766572733300105336788122023542180975125454"
"05947522435258490771167055601360483958644670" "05947522435258490771167055601360483958644670"
"63244157221553975369781797784617406495514929" "63244157221553975369781797784617406495514929"
"08625693219784686224828397224137565705605749" "08625693219784686224828397224137565705605749"
"02614079729686524145351004748216637048440319" "02614079729686524145351004748216637048440319"
"98900088952434506585412275886668811642717147" "98900088952434506585412275886668811642717147"
"99244429282308634656748139191231628245861786" "99244429282308634656748139191231628245861786"
"64583591245665294765456828489128831426076900" "64583591245665294765456828489128831426076900"
"42242190226710556263211111093705442175069416" "42242190226710556263211111093705442175069416"
"58960408071984038509624554443629812309878799" "58960408071984038509624554443629812309878799"
"27244284909188845801561660979191338754992005" "27244284909188845801561660979191338754992005"
"24063689912560717606058861164671094050775410" "24063689912560717606058861164671094050775410"
"02256983155200055935729725716362695618826704" "02256983155200055935729725716362695618826704"
"28252483600823257530420752963450"; "28252483600823257530420752963450";
char cur, out; char cur, out;
long int max = 0, tmp = 1; long int max = 0, tmp = 1;
int i, j; int i, j;
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
for(i = 0; i < 1000; i++) for(i = 0; i < 1000; i++)
{ {
/* For the first 13 digits, just multiply them.*/ /* For the first 13 digits, just multiply them.*/
if(i < 13) if(i < 13)
{ {
cur = string[i] - '0';
tmp *= (long int)cur;
}
else
{
/* If the current product is greater than the maximum, save the current as maximum.*/
if(tmp > max)
{
max = tmp;
}
/* Check the value of the first digit of the previous sequence, which will not be part
* of the next sequence.*/
out = string[i-13] - '0';
/* If the digit is zero, multiply all the 13 digits of the new sequence.*/
if(out == 0)
{
tmp = 1;
for(j = i - 12; j <= i; j++)
{
cur = string[j] - '0';
tmp *= (long int)cur;
}
}
/* If the digit not zero, instead of multiplying all the 13 digits of the new sequence,
* divide the current product by the remove digit and multiply it by the new digit.*/
else
{
cur = string[i] - '0'; cur = string[i] - '0';
tmp /= (long int)out;
tmp *= (long int)cur; tmp *= (long int)cur;
} }
} else
} {
/* If the current product is greater than the maximum, save the current as maximum.*/
if(tmp > max)
{
max = tmp;
}
/* Check the value of the first digit of the previous sequence, which will not be part
* of the next sequence.*/
out = string[i-13] - '0';
/* If the digit is zero, multiply all the 13 digits of the new sequence.*/
if(out == 0)
{
tmp = 1;
for(j = i - 12; j <= i; j++)
{
cur = string[j] - '0';
tmp *= (long int)cur;
}
}
/* If the digit not zero, instead of multiplying all the 13 digits of the new sequence,
* divide the current product by the remove digit and multiply it by the new digit.*/
else
{
cur = string[i] - '0';
tmp /= (long int)out;
tmp *= (long int)cur;
}
}
}
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 8\n"); printf("Project Euler, Problem 8\n");
printf("Answer: %ld\n", max); printf("Answer: %ld\n", max);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0; return 0;
} }

View File

@ -8,6 +8,8 @@
* *
* Find the product abc.*/ * Find the product abc.*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <time.h> #include <time.h>
@ -15,61 +17,61 @@
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int a, b, c, tmpa, tmpb, tmpc, i, m, n, found = 0; int a, b, c, tmpa, tmpb, tmpc, i, m, n, found = 0;
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
/* Brute force approach: generate all the Pythagorean triplets using /* Brute force approach: generate all the Pythagorean triplets using
* Euclid's formula, until the one where a+b+c=1000 is found.*/ * Euclid's formula, until the one where a+b+c=1000 is found.*/
for(m = 2; found == 0; m++) for(m = 2; found == 0; m++)
{ {
for(n = 1; n < m && !found; n++) for(n = 1; n < m && !found; n++)
{ {
if(gcd(m, n) == 1 && ((m % 2 == 0 && n % 2 != 0) || (m % 2 != 0 && n % 2 == 0))) if(gcd(m, n) == 1 && ((m % 2 == 0 && n % 2 != 0) || (m % 2 != 0 && n % 2 == 0)))
{
a = m * m - n * n;
b = 2 * m * n;
c = m * m + n * n;
if(a + b + c == 1000)
{ {
found = 1; a = m * m - n * n;
break; b = 2 * m * n;
c = m * m + n * n;
if(a + b + c == 1000)
{
found = 1;
break;
}
i = 2;
do
{
tmpa = a * i;
tmpb = b * i;
tmpc = c * i;
if(tmpa + tmpb + tmpc == 1000)
{
a = tmpa;
b = tmpb;
c = tmpc;
found = 1;
break;
}
i++;
} while(tmpa + tmpb + tmpc < 1000);
} }
}
}
i = 2; clock_gettime(CLOCK_MONOTONIC, &end);
do elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
{
tmpa = a * i;
tmpb = b * i;
tmpc = c * i;
if(tmpa + tmpb + tmpc == 1000) printf("Project Euler, Problem 9\n");
{ printf("Answer: %d\n", a*b*c);
a = tmpa;
b = tmpb;
c = tmpc;
found = 1;
break;
}
i++; printf("Elapsed time: %.9lf seconds\n", elapsed);
}while(tmpa + tmpb + tmpc < 1000);
}
}
}
clock_gettime(CLOCK_MONOTONIC, &end); return 0;
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 9\n");
printf("Answer: %d\n", a*b*c);
printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0;
} }

View File

@ -2,6 +2,8 @@
* *
* Find the sum of all the primes below two million.*/ * Find the sum of all the primes below two million.*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <time.h> #include <time.h>
@ -11,41 +13,41 @@
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int i; int i;
int *primes; int *primes;
long int sum = 0; long int sum = 0;
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
/* Use the function in projecteuler.c implementing the /* Use the function in projecteuler.c implementing the
* Sieve of Eratosthenes algorithm to generate primes.*/ * Sieve of Eratosthenes algorithm to generate primes.*/
if((primes = sieve(N)) == NULL) if((primes = sieve(N)) == NULL)
{ {
fprintf(stderr, "Error! Sieve function returned NULL\n"); fprintf(stderr, "Error! Sieve function returned NULL\n");
return 1; return 1;
} }
/* Sum all the primes.*/ /* Sum all the primes.*/
for(i = 0; i < N; i++) for(i = 0; i < N; i++)
{ {
if(primes[i]) if(primes[i])
{ {
sum += i; sum += i;
} }
} }
free(primes); free(primes);
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 10\n"); printf("Project Euler, Problem 10\n");
printf("Answer: %ld\n", sum); printf("Answer: %ld\n", sum);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0; return 0;
} }

179
C/p011.c
View File

@ -25,110 +25,113 @@
* *
* What is the greatest product of four adjacent numbers in the same direction (up, down, left, right, or diagonally) in the 20×20 grid?*/ * What is the greatest product of four adjacent numbers in the same direction (up, down, left, right, or diagonally) in the 20×20 grid?*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <time.h> #include <time.h>
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int grid[][20] = {{8, 2, 22, 97, 38, 15, 0, 40, 0, 75, 4, 5, 7, 78, 52, 12, 50, 77, 91, 8}, int grid[][20] = {{8, 2, 22, 97, 38, 15, 0, 40, 0, 75, 4, 5, 7, 78, 52, 12, 50, 77, 91, 8},
{49, 49, 99, 40, 17, 81, 18, 57, 60, 87, 17, 40, 98, 43, 69, 48, 4, 56, 62, 0}, {49, 49, 99, 40, 17, 81, 18, 57, 60, 87, 17, 40, 98, 43, 69, 48, 4, 56, 62, 0},
{81, 49, 31, 73, 55, 79, 14, 29, 93, 71, 40, 67, 53, 88, 30, 3, 49, 13, 36, 65}, {81, 49, 31, 73, 55, 79, 14, 29, 93, 71, 40, 67, 53, 88, 30, 3, 49, 13, 36, 65},
{52, 70, 95, 23, 4, 60, 11, 42, 69, 24, 68, 56, 1, 32, 56, 71, 37, 2, 36, 91}, {52, 70, 95, 23, 4, 60, 11, 42, 69, 24, 68, 56, 1, 32, 56, 71, 37, 2, 36, 91},
{22, 31, 16, 71, 51, 67, 63, 89, 41, 92, 36, 54, 22, 40, 40, 28, 66, 33, 13, 80}, {22, 31, 16, 71, 51, 67, 63, 89, 41, 92, 36, 54, 22, 40, 40, 28, 66, 33, 13, 80},
{24, 47, 32, 60, 99, 3, 45, 2, 44, 75, 33, 53, 78, 36, 84, 20, 35, 17, 12, 50}, {24, 47, 32, 60, 99, 3, 45, 2, 44, 75, 33, 53, 78, 36, 84, 20, 35, 17, 12, 50},
{32, 98, 81, 28, 64, 23, 67, 10, 26, 38, 40, 67, 59, 54, 70, 66, 18, 38, 64, 70}, {32, 98, 81, 28, 64, 23, 67, 10, 26, 38, 40, 67, 59, 54, 70, 66, 18, 38, 64, 70},
{67, 26, 20, 68, 2, 62, 12, 20, 95, 63, 94, 39, 63, 8, 40, 91, 66, 49, 94, 21}, {67, 26, 20, 68, 2, 62, 12, 20, 95, 63, 94, 39, 63, 8, 40, 91, 66, 49, 94, 21},
{24, 55, 58, 5, 66, 73, 99, 26, 97, 17, 78, 78, 96, 83, 14, 88, 34, 89, 63, 72}, {24, 55, 58, 5, 66, 73, 99, 26, 97, 17, 78, 78, 96, 83, 14, 88, 34, 89, 63, 72},
{21, 36, 23, 9, 75, 0, 76, 44, 20, 45, 35, 14, 0, 61, 33, 97, 34, 31, 33, 95}, {21, 36, 23, 9, 75, 0, 76, 44, 20, 45, 35, 14, 0, 61, 33, 97, 34, 31, 33, 95},
{78, 17, 53, 28, 22, 75, 31, 67, 15, 94, 3, 80, 4, 62, 16, 14, 9, 53, 56, 92}, {78, 17, 53, 28, 22, 75, 31, 67, 15, 94, 3, 80, 4, 62, 16, 14, 9, 53, 56, 92},
{16, 39, 5, 42, 96, 35, 31, 47, 55, 58, 88, 24, 0, 17, 54, 24, 36, 29, 85, 57}, {16, 39, 5, 42, 96, 35, 31, 47, 55, 58, 88, 24, 0, 17, 54, 24, 36, 29, 85, 57},
{86, 56, 0, 48, 35, 71, 89, 7, 5, 44, 44, 37, 44, 60, 21, 58, 51, 54, 17, 58}, {86, 56, 0, 48, 35, 71, 89, 7, 5, 44, 44, 37, 44, 60, 21, 58, 51, 54, 17, 58},
{19, 80, 81, 68, 5, 94, 47, 69, 28, 73, 92, 13, 86, 52, 17, 77, 4, 89, 55, 40}, {19, 80, 81, 68, 5, 94, 47, 69, 28, 73, 92, 13, 86, 52, 17, 77, 4, 89, 55, 40},
{4, 52, 8, 83, 97, 35, 99, 16, 7, 97, 57, 32, 16, 26, 26, 79, 33, 27, 98, 66}, {4, 52, 8, 83, 97, 35, 99, 16, 7, 97, 57, 32, 16, 26, 26, 79, 33, 27, 98, 66},
{88, 36, 68, 87, 57, 62, 20, 72, 3, 46, 33, 67, 46, 55, 12, 32, 63, 93, 53, 69}, {88, 36, 68, 87, 57, 62, 20, 72, 3, 46, 33, 67, 46, 55, 12, 32, 63, 93, 53, 69},
{4, 42, 16, 73, 38, 25, 39, 11, 24, 94, 72, 18, 8, 46, 29, 32, 40, 62, 76, 36}, {4, 42, 16, 73, 38, 25, 39, 11, 24, 94, 72, 18, 8, 46, 29, 32, 40, 62, 76, 36},
{20, 69, 36, 41, 72, 30, 23, 88, 34, 62, 99, 69, 82, 67, 59, 85, 74, 4, 36, 16}, {20, 69, 36, 41, 72, 30, 23, 88, 34, 62, 99, 69, 82, 67, 59, 85, 74, 4, 36, 16},
{20, 73, 35, 29, 78, 31, 90, 1, 74, 31, 49, 71, 48, 86, 81, 16, 23, 57, 5, 54}, {20, 73, 35, 29, 78, 31, 90, 1, 74, 31, 49, 71, 48, 86, 81, 16, 23, 57, 5, 54},
{1, 70, 54, 71, 83, 51, 54, 69, 16, 92, 33, 48, 61, 43, 52, 1, 89, 19, 67, 48}}; {1, 70, 54, 71, 83, 51, 54, 69, 16, 92, 33, 48, 61, 43, 52, 1, 89, 19, 67, 48}
int i, j, k, w, max = 0, prod; };
double elapsed; int i, j, k, w, max = 0, prod;
struct timespec start, end; double elapsed;
struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
/* Brute-force approach: for each number in the grid, try products with its three /* Brute-force approach: for each number in the grid, try products with its three
* adjacent numbers in every direction (horizontal, vertical and the two diagonals). * adjacent numbers in every direction (horizontal, vertical and the two diagonals).
* If the product is larger than the current maximum, save it.*/ * If the product is larger than the current maximum, save it.*/
for(i = 0; i < 17; i++) for(i = 0; i < 17; i++)
{ {
for(j = 0; j < 17; j++) for(j = 0; j < 17; j++)
{ {
prod = 1; prod = 1;
/* Horizontal direction.*/ /* Horizontal direction.*/
for(k = j; k < j + 4; k++) for(k = j; k < j + 4; k++)
{ {
prod *= grid[i][k]; prod *= grid[i][k];
} }
if(prod > max)
{
max = prod;
}
prod = 1;
/* Vertical direction.*/
for(k = i; k < i + 4; k++)
{
prod *= grid[k][j];
}
if(prod > max)
{
max = prod;
}
prod = 1;
/* Diagonal direction, from top left to bottom right.*/
for(k = i, w = j; k < i + 4 && w < j + 4; k++, w++)
{
prod *= grid[k][w];
}
if(k == i + 4 && w == j + 4)
{
if(prod > max) if(prod > max)
{ {
max = prod; max = prod;
} }
}
}
}
/* The last diagonal is handled separately.*/ prod = 1;
for(i = 0; i < 17; i++) /* Vertical direction.*/
{ for(k = i; k < i + 4; k++)
for(j = 3; j < 20; j++) {
{ prod *= grid[k][j];
prod = 1; }
/* Diagonal direction, from top right to bottom left.*/ if(prod > max)
for(k = i, w = j; k < i + 4 && w > j - 4; k++, w--) {
{ max = prod;
prod *= grid[k][w]; }
}
if(prod > max)
{
max = prod;
}
}
}
clock_gettime(CLOCK_MONOTONIC, &end); prod = 1;
/* Diagonal direction, from top left to bottom right.*/
for(k = i, w = j; k < i + 4 && w < j + 4; k++, w++)
{
prod *= grid[k][w];
}
if(k == i + 4 && w == j + 4)
{
if(prod > max)
{
max = prod;
}
}
}
}
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; /* The last diagonal is handled separately.*/
for(i = 0; i < 17; i++)
{
for(j = 3; j < 20; j++)
{
prod = 1;
/* Diagonal direction, from top right to bottom left.*/
for(k = i, w = j; k < i + 4 && w > j - 4; k++, w--)
{
prod *= grid[k][w];
}
if(prod > max)
{
max = prod;
}
}
}
printf("Project Euler, Problem 11\n"); clock_gettime(CLOCK_MONOTONIC, &end);
printf("Answer: %d\n", max);
printf("Elapsed time: %.9lf seconds\n", elapsed); elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
return 0; printf("Project Euler, Problem 11\n");
printf("Answer: %d\n", max);
printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0;
} }

View File

@ -17,6 +17,8 @@
* *
* What is the value of the first triangle number to have over five hundred divisors?*/ * What is the value of the first triangle number to have over five hundred divisors?*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <time.h> #include <time.h>
@ -24,34 +26,34 @@
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int i = 0, finished = 0, count, triang = 0; int i = 0, finished = 0, count, triang = 0;
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
/* Generate all triangle numbers until the first one with more than 500 divisors is found.*/ /* Generate all triangle numbers until the first one with more than 500 divisors is found.*/
while(!finished) while(!finished)
{ {
i++; i++;
triang += i; triang += i;
/* Use the function implemented in projecteuler.c to count divisors of a number.*/ /* Use the function implemented in projecteuler.c to count divisors of a number.*/
count = count_divisors(triang); count = count_divisors(triang);
if(count > 500) if(count > 500)
{ {
finished = 1; finished = 1;
} }
} }
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 12\n"); printf("Project Euler, Problem 12\n");
printf("Answer: %d\n", triang); printf("Answer: %d\n", triang);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0; return 0;
} }

159
C/p013.c
View File

@ -101,6 +101,8 @@
* 20849603980134001723930671666823555245252804609722 * 20849603980134001723930671666823555245252804609722
* 53503534226472524250874054075591789781264330331690*/ * 53503534226472524250874054075591789781264330331690*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <time.h> #include <time.h>
@ -108,94 +110,95 @@
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
char n[100][51] = {"37107287533902102798797998220837590246510135740250", "46376937677490009712648124896970078050417018260538", char n[100][51] = {"37107287533902102798797998220837590246510135740250", "46376937677490009712648124896970078050417018260538",
"74324986199524741059474233309513058123726617309629", "91942213363574161572522430563301811072406154908250", "74324986199524741059474233309513058123726617309629", "91942213363574161572522430563301811072406154908250",
"23067588207539346171171980310421047513778063246676", "89261670696623633820136378418383684178734361726757", "23067588207539346171171980310421047513778063246676", "89261670696623633820136378418383684178734361726757",
"28112879812849979408065481931592621691275889832738", "44274228917432520321923589422876796487670272189318", "28112879812849979408065481931592621691275889832738", "44274228917432520321923589422876796487670272189318",
"47451445736001306439091167216856844588711603153276", "70386486105843025439939619828917593665686757934951", "47451445736001306439091167216856844588711603153276", "70386486105843025439939619828917593665686757934951",
"62176457141856560629502157223196586755079324193331", "64906352462741904929101432445813822663347944758178", "62176457141856560629502157223196586755079324193331", "64906352462741904929101432445813822663347944758178",
"92575867718337217661963751590579239728245598838407", "58203565325359399008402633568948830189458628227828", "92575867718337217661963751590579239728245598838407", "58203565325359399008402633568948830189458628227828",
"80181199384826282014278194139940567587151170094390", "35398664372827112653829987240784473053190104293586", "80181199384826282014278194139940567587151170094390", "35398664372827112653829987240784473053190104293586",
"86515506006295864861532075273371959191420517255829", "71693888707715466499115593487603532921714970056938", "86515506006295864861532075273371959191420517255829", "71693888707715466499115593487603532921714970056938",
"54370070576826684624621495650076471787294438377604", "53282654108756828443191190634694037855217779295145", "54370070576826684624621495650076471787294438377604", "53282654108756828443191190634694037855217779295145",
"36123272525000296071075082563815656710885258350721", "45876576172410976447339110607218265236877223636045", "36123272525000296071075082563815656710885258350721", "45876576172410976447339110607218265236877223636045",
"17423706905851860660448207621209813287860733969412", "81142660418086830619328460811191061556940512689692", "17423706905851860660448207621209813287860733969412", "81142660418086830619328460811191061556940512689692",
"51934325451728388641918047049293215058642563049483", "62467221648435076201727918039944693004732956340691", "51934325451728388641918047049293215058642563049483", "62467221648435076201727918039944693004732956340691",
"15732444386908125794514089057706229429197107928209", "55037687525678773091862540744969844508330393682126", "15732444386908125794514089057706229429197107928209", "55037687525678773091862540744969844508330393682126",
"18336384825330154686196124348767681297534375946515", "80386287592878490201521685554828717201219257766954", "18336384825330154686196124348767681297534375946515", "80386287592878490201521685554828717201219257766954",
"78182833757993103614740356856449095527097864797581", "16726320100436897842553539920931837441497806860984", "78182833757993103614740356856449095527097864797581", "16726320100436897842553539920931837441497806860984",
"48403098129077791799088218795327364475675590848030", "87086987551392711854517078544161852424320693150332", "48403098129077791799088218795327364475675590848030", "87086987551392711854517078544161852424320693150332",
"59959406895756536782107074926966537676326235447210", "69793950679652694742597709739166693763042633987085", "59959406895756536782107074926966537676326235447210", "69793950679652694742597709739166693763042633987085",
"41052684708299085211399427365734116182760315001271", "65378607361501080857009149939512557028198746004375", "41052684708299085211399427365734116182760315001271", "65378607361501080857009149939512557028198746004375",
"35829035317434717326932123578154982629742552737307", "94953759765105305946966067683156574377167401875275", "35829035317434717326932123578154982629742552737307", "94953759765105305946966067683156574377167401875275",
"88902802571733229619176668713819931811048770190271", "25267680276078003013678680992525463401061632866526", "88902802571733229619176668713819931811048770190271", "25267680276078003013678680992525463401061632866526",
"36270218540497705585629946580636237993140746255962", "24074486908231174977792365466257246923322810917141", "36270218540497705585629946580636237993140746255962", "24074486908231174977792365466257246923322810917141",
"91430288197103288597806669760892938638285025333403", "34413065578016127815921815005561868836468420090470", "91430288197103288597806669760892938638285025333403", "34413065578016127815921815005561868836468420090470",
"23053081172816430487623791969842487255036638784583", "11487696932154902810424020138335124462181441773470", "23053081172816430487623791969842487255036638784583", "11487696932154902810424020138335124462181441773470",
"63783299490636259666498587618221225225512486764533", "67720186971698544312419572409913959008952310058822", "63783299490636259666498587618221225225512486764533", "67720186971698544312419572409913959008952310058822",
"95548255300263520781532296796249481641953868218774", "76085327132285723110424803456124867697064507995236", "95548255300263520781532296796249481641953868218774", "76085327132285723110424803456124867697064507995236",
"37774242535411291684276865538926205024910326572967", "23701913275725675285653248258265463092207058596522", "37774242535411291684276865538926205024910326572967", "23701913275725675285653248258265463092207058596522",
"29798860272258331913126375147341994889534765745501", "18495701454879288984856827726077713721403798879715", "29798860272258331913126375147341994889534765745501", "18495701454879288984856827726077713721403798879715",
"38298203783031473527721580348144513491373226651381", "34829543829199918180278916522431027392251122869539", "38298203783031473527721580348144513491373226651381", "34829543829199918180278916522431027392251122869539",
"40957953066405232632538044100059654939159879593635", "29746152185502371307642255121183693803580388584903", "40957953066405232632538044100059654939159879593635", "29746152185502371307642255121183693803580388584903",
"41698116222072977186158236678424689157993532961922", "62467957194401269043877107275048102390895523597457", "41698116222072977186158236678424689157993532961922", "62467957194401269043877107275048102390895523597457",
"23189706772547915061505504953922979530901129967519", "86188088225875314529584099251203829009407770775672", "23189706772547915061505504953922979530901129967519", "86188088225875314529584099251203829009407770775672",
"11306739708304724483816533873502340845647058077308", "82959174767140363198008187129011875491310547126581", "11306739708304724483816533873502340845647058077308", "82959174767140363198008187129011875491310547126581",
"97623331044818386269515456334926366572897563400500", "42846280183517070527831839425882145521227251250327", "97623331044818386269515456334926366572897563400500", "42846280183517070527831839425882145521227251250327",
"55121603546981200581762165212827652751691296897789", "32238195734329339946437501907836945765883352399886", "55121603546981200581762165212827652751691296897789", "32238195734329339946437501907836945765883352399886",
"75506164965184775180738168837861091527357929701337", "62177842752192623401942399639168044983993173312731", "75506164965184775180738168837861091527357929701337", "62177842752192623401942399639168044983993173312731",
"32924185707147349566916674687634660915035914677504", "99518671430235219628894890102423325116913619626622", "32924185707147349566916674687634660915035914677504", "99518671430235219628894890102423325116913619626622",
"73267460800591547471830798392868535206946944540724", "76841822524674417161514036427982273348055556214818", "73267460800591547471830798392868535206946944540724", "76841822524674417161514036427982273348055556214818",
"97142617910342598647204516893989422179826088076852", "87783646182799346313767754307809363333018982642090", "97142617910342598647204516893989422179826088076852", "87783646182799346313767754307809363333018982642090",
"10848802521674670883215120185883543223812876952786", "71329612474782464538636993009049310363619763878039", "10848802521674670883215120185883543223812876952786", "71329612474782464538636993009049310363619763878039",
"62184073572399794223406235393808339651327408011116", "66627891981488087797941876876144230030984490851411", "62184073572399794223406235393808339651327408011116", "66627891981488087797941876876144230030984490851411",
"60661826293682836764744779239180335110989069790714", "85786944089552990653640447425576083659976645795096", "60661826293682836764744779239180335110989069790714", "85786944089552990653640447425576083659976645795096",
"66024396409905389607120198219976047599490197230297", "64913982680032973156037120041377903785566085089252", "66024396409905389607120198219976047599490197230297", "64913982680032973156037120041377903785566085089252",
"16730939319872750275468906903707539413042652315011", "94809377245048795150954100921645863754710598436791", "16730939319872750275468906903707539413042652315011", "94809377245048795150954100921645863754710598436791",
"78639167021187492431995700641917969777599028300699", "15368713711936614952811305876380278410754449733078", "78639167021187492431995700641917969777599028300699", "15368713711936614952811305876380278410754449733078",
"40789923115535562561142322423255033685442488917353", "44889911501440648020369068063960672322193204149535", "40789923115535562561142322423255033685442488917353", "44889911501440648020369068063960672322193204149535",
"41503128880339536053299340368006977710650566631954", "81234880673210146739058568557934581403627822703280", "41503128880339536053299340368006977710650566631954", "81234880673210146739058568557934581403627822703280",
"82616570773948327592232845941706525094512325230608", "22918802058777319719839450180888072429661980811197", "82616570773948327592232845941706525094512325230608", "22918802058777319719839450180888072429661980811197",
"77158542502016545090413245809786882778948721859617", "72107838435069186155435662884062257473692284509516", "77158542502016545090413245809786882778948721859617", "72107838435069186155435662884062257473692284509516",
"20849603980134001723930671666823555245252804609722", "53503534226472524250874054075591789781264330331690"}; "20849603980134001723930671666823555245252804609722", "53503534226472524250874054075591789781264330331690"
char result[100]; };
int i; char result[100];
double elapsed; int i;
struct timespec start, end; double elapsed;
mpz_t a, b; struct timespec start, end;
mpz_t a, b;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
/* Using the GNU Multiple Precision Arithmetic Library (GMP) /* Using the GNU Multiple Precision Arithmetic Library (GMP)
* to sum the numbers and get the first 10 digits of the sum.*/ * to sum the numbers and get the first 10 digits of the sum.*/
mpz_inits(a, b, NULL); mpz_inits(a, b, NULL);
mpz_set_str(a, n[0], 10); mpz_set_str(a, n[0], 10);
for(i = 1; i < 100; i++) for(i = 1; i < 100; i++)
{ {
mpz_set_str(b, n[i], 10); mpz_set_str(b, n[i], 10);
mpz_add(a, a, b); mpz_add(a, a, b);
} }
gmp_sprintf(result, "%Zd\n", a); gmp_sprintf(result, "%Zd\n", a);
mpz_clears(a, b, NULL); mpz_clears(a, b, NULL);
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec-start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec-start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 13\n"); printf("Project Euler, Problem 13\n");
printf("Answer: "); printf("Answer: ");
for(i = 0; i < 10; i++) for(i = 0; i < 10; i++)
{ {
printf("%c", result[i]); printf("%c", result[i]);
} }
printf("\n"); printf("\n");
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0; return 0;
} }

View File

@ -14,6 +14,8 @@
* *
* NOTE: Once the chain starts the terms are allowed to go above one million.*/ * NOTE: Once the chain starts the terms are allowed to go above one million.*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <time.h> #include <time.h>
@ -26,36 +28,36 @@ int collatz_found[N] = {0};
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int i, count, max = 0, max_l = 0; int i, count, max = 0, max_l = 0;
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
for(i = 1; i < N; i++) for(i = 1; i < N; i++)
{ {
/* For each number from 1 to 1000000, find the length of the sequence /* For each number from 1 to 1000000, find the length of the sequence
* and save its value, so that it can be used for the next numbers.*/ * and save its value, so that it can be used for the next numbers.*/
count = collatz_length(i); count = collatz_length(i);
collatz_found[i] = count; collatz_found[i] = count;
if(count > max_l) if(count > max_l)
{ {
max_l = count; max_l = count;
max = i; max = i;
} }
} }
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 14\n"); printf("Project Euler, Problem 14\n");
printf("Answer: %d\n", max); printf("Answer: %d\n", max);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0; return 0;
} }
/* Recursive function to calculate the Collatz sequence for n. /* Recursive function to calculate the Collatz sequence for n.
@ -63,16 +65,16 @@ int main(int argc, char **argv)
* Collatz(n)=1+Collatz(3*n+1).*/ * Collatz(n)=1+Collatz(3*n+1).*/
int collatz_length(long int n) int collatz_length(long int n)
{ {
if(n == 1) if(n == 1)
return 1; return 1;
/* If Collatz(n) has been previously calculated, /* If Collatz(n) has been previously calculated,
* just return the value.*/ * just return the value.*/
if(n < N && collatz_found[n]) if(n < N && collatz_found[n])
return collatz_found[n]; return collatz_found[n];
if(n % 2 == 0) if(n % 2 == 0)
return 1 + collatz_length(n/2); return 1 + collatz_length(n/2);
else else
return 1 + collatz_length(3*n+1); return 1 + collatz_length(3*n+1);
} }

View File

@ -1,6 +1,8 @@
/* Starting in the top left corner of a 2×2 grid, and only being able to move to the right and down, there are exactly 6 routes to the bottom right corner /* Starting in the top left corner of a 2×2 grid, and only being able to move to the right and down, there are exactly 6 routes to the bottom right corner
* How many such routes are there through a 20×20 grid?*/ * How many such routes are there through a 20×20 grid?*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <time.h> #include <time.h>
@ -8,33 +10,33 @@
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
mpz_t count, tmp; mpz_t count, tmp;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
/* Using a combinatorial solution: in a 20x20 grid there will always be /* Using a combinatorial solution: in a 20x20 grid there will always be
* 20 movements to the right and 20 movements down, that can be represented * 20 movements to the right and 20 movements down, that can be represented
* as a string of Rs and Ds. The number of routes is the number of combinations. * as a string of Rs and Ds. The number of routes is the number of combinations.
* This is obtained calculating n!/(k!*(n-k)!), where n=40 and k=20. The GMP * This is obtained calculating n!/(k!*(n-k)!), where n=40 and k=20. The GMP
* Library is used to calculate the factorials.*/ * Library is used to calculate the factorials.*/
mpz_inits(count, tmp, NULL); mpz_inits(count, tmp, NULL);
mpz_fac_ui(count, 40); mpz_fac_ui(count, 40);
mpz_fac_ui(tmp, 20); mpz_fac_ui(tmp, 20);
mpz_mul(tmp, tmp, tmp); mpz_mul(tmp, tmp, tmp);
mpz_tdiv_q(count, count, tmp); mpz_tdiv_q(count, count, tmp);
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 15\n"); printf("Project Euler, Problem 15\n");
gmp_printf("Answer: %Zd\n", count); gmp_printf("Answer: %Zd\n", count);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
mpz_clears(count, tmp, NULL); mpz_clears(count, tmp, NULL);
return 0; return 0;
} }

View File

@ -2,6 +2,8 @@
* *
* What is the sum of the digits of the number 2^1000?*/ * What is the sum of the digits of the number 2^1000?*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <time.h> #include <time.h>
@ -9,37 +11,37 @@
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
mpz_t p, sum, r; mpz_t p, sum, r;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
/* Simply calculate 2^1000 with the GMP Library /* Simply calculate 2^1000 with the GMP Library
* and sum all the digits.*/ * and sum all the digits.*/
mpz_init_set_ui(p, 2); mpz_init_set_ui(p, 2);
mpz_init_set_ui(sum, 0); mpz_init_set_ui(sum, 0);
mpz_init(r); mpz_init(r);
mpz_pow_ui(p, p, 1000); mpz_pow_ui(p, p, 1000);
while(mpz_cmp_ui(p, 0)) while(mpz_cmp_ui(p, 0))
{ {
/* To get each digit, simply get the reminder of the division by 10.*/ /* To get each digit, simply get the reminder of the division by 10.*/
mpz_tdiv_qr_ui(p, r, p, 10); mpz_tdiv_qr_ui(p, r, p, 10);
mpz_add(sum, sum, r); mpz_add(sum, sum, r);
} }
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 16\n"); printf("Project Euler, Problem 16\n");
gmp_printf("Answer: %Zd\n", sum); gmp_printf("Answer: %Zd\n", sum);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
mpz_clears(p, sum, r, NULL); mpz_clears(p, sum, r, NULL);
return 0; return 0;
} }

118
C/p017.c
View File

@ -5,78 +5,80 @@
* NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) contains 23 letters and 115 (one hundred and fifteen) * NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) contains 23 letters and 115 (one hundred and fifteen)
* contains 20 letters. The use of "and" when writing out numbers is in compliance with British usage.*/ * contains 20 letters. The use of "and" when writing out numbers is in compliance with British usage.*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <time.h> #include <time.h>
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
/* Number of letters for numbers from 1 to 19.*/ /* Number of letters for numbers from 1 to 19.*/
int n1_19[19] = {3, 3, 5, 4, 4, 3, 5, 5, 4, 3, 6, 6, 8, 8, 7, 7, 9, 8, 8}; int n1_19[19] = {3, 3, 5, 4, 4, 3, 5, 5, 4, 3, 6, 6, 8, 8, 7, 7, 9, 8, 8};
/* Number of letters for "twenty", "thirty", ..., "ninety".*/ /* Number of letters for "twenty", "thirty", ..., "ninety".*/
int n20_90[8] = {6, 6, 5, 5, 5, 7, 6, 6}; int n20_90[8] = {6, 6, 5, 5, 5, 7, 6, 6};
/* Number of letters for "one hundred and", "two hundred and", ..., /* Number of letters for "one hundred and", "two hundred and", ...,
* "nine hundred and".*/ * "nine hundred and".*/
int n100_900[9] = {13, 13, 15, 14, 14, 13, 15, 15, 14}; int n100_900[9] = {13, 13, 15, 14, 14, 13, 15, 15, 14};
/* Number of letters for 1000.*/ /* Number of letters for 1000.*/
int n1000 = 11; int n1000 = 11;
int sum = 0, i, j; int sum = 0, i, j;
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
/* Sum the letters of the first 19 numbers.*/ /* Sum the letters of the first 19 numbers.*/
for(i = 0; i < 19; i++) for(i = 0; i < 19; i++)
{ {
sum += n1_19[i]; sum += n1_19[i];
} }
/* Add the letters of the numbers from 20 to 99.*/ /* Add the letters of the numbers from 20 to 99.*/
for(i = 0; i < 8; i++) for(i = 0; i < 8; i++)
{ {
/* "Twenty", "thirty", ... "ninety" are used ten times each /* "Twenty", "thirty", ... "ninety" are used ten times each
* (e.g. "twenty", "twenty one", "twenty two", ..., "twenty nine").*/ * (e.g. "twenty", "twenty one", "twenty two", ..., "twenty nine").*/
n20_90[i] *= 10; n20_90[i] *= 10;
/* Add "one", "two", ..., "nine".*/ /* Add "one", "two", ..., "nine".*/
for(j = 0; j < 9; j++) for(j = 0; j < 9; j++)
{ {
n20_90[i] += n1_19[j]; n20_90[i] += n1_19[j];
} }
sum += n20_90[i]; sum += n20_90[i];
} }
/* Add the letters of the numbers from 100 to 999.*/ /* Add the letters of the numbers from 100 to 999.*/
for(i = 0; i < 9; i++) for(i = 0; i < 9; i++)
{ {
/* "One hundred and", "two hundred and",... are used 100 times each.*/ /* "One hundred and", "two hundred and",... are used 100 times each.*/
n100_900[i] *= 100; n100_900[i] *= 100;
/* Add "one" to "nineteen".*/ /* Add "one" to "nineteen".*/
for(j = 0; j < 19; j++) for(j = 0; j < 19; j++)
{ {
n100_900[i] += n1_19[j]; n100_900[i] += n1_19[j];
} }
/* Add "twenty" to "ninety nine", previously calculated.*/ /* Add "twenty" to "ninety nine", previously calculated.*/
for(j = 0; j < 8; j++) for(j = 0; j < 8; j++)
{ {
n100_900[i] += n20_90[j]; n100_900[i] += n20_90[j];
} }
/* "One hundred", "two hundred", ... don't have the "and", so remove /* "One hundred", "two hundred", ... don't have the "and", so remove
* three letters for each of them.*/ * three letters for each of them.*/
sum += n100_900[i] - 3; sum += n100_900[i] - 3;
} }
/* Add "one thousand".*/ /* Add "one thousand".*/
sum += n1000; sum += n1000;
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 17\n"); printf("Project Euler, Problem 17\n");
printf("Answer: %d\n", sum); printf("Answer: %d\n", sum);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0; return 0;
} }

View File

@ -28,6 +28,8 @@
* NOTE: As there are only 16384 routes, it is possible to solve this problem by trying every route. However, Problem 67, is the same challenge * NOTE: As there are only 16384 routes, it is possible to solve this problem by trying every route. However, Problem 67, is the same challenge
* with a triangle containing one-hundred rows; it cannot be solved by brute force, and requires a clever method! ;o)*/ * with a triangle containing one-hundred rows; it cannot be solved by brute force, and requires a clever method! ;o)*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <time.h> #include <time.h>
@ -35,63 +37,63 @@
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int i, j, max; int i, j, max;
int **triang; int **triang;
double elapsed; double elapsed;
FILE *fp; FILE *fp;
struct timespec start, end; struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
if((triang = (int **)malloc(15*sizeof(int *))) == NULL) if((triang = (int **)malloc(15*sizeof(int *))) == NULL)
{ {
fprintf(stderr, "Error while allocating memory\n"); fprintf(stderr, "Error while allocating memory\n");
return 1; return 1;
} }
for(i = 1; i <= 15; i++) for(i = 1; i <= 15; i++)
{ {
if((triang[i-1] = (int *)malloc(i*sizeof(int))) == NULL) if((triang[i-1] = (int *)malloc(i*sizeof(int))) == NULL)
{ {
fprintf(stderr, "Error while allocating memory\n"); fprintf(stderr, "Error while allocating memory\n");
return 1; return 1;
} }
} }
if((fp = fopen("triang.txt", "r")) == NULL) if((fp = fopen("triang.txt", "r")) == NULL)
{ {
fprintf(stderr, "Error while opening file %s\n", "triang.txt"); fprintf(stderr, "Error while opening file %s\n", "triang.txt");
return 1; return 1;
} }
for(i = 1; i <= 15; i++) for(i = 1; i <= 15; i++)
{ {
for(j = 0; j < i; j++) for(j = 0; j < i; j++)
{ {
fscanf(fp, "%d", &triang[i-1][j]); fscanf(fp, "%d", &triang[i-1][j]);
} }
} }
fclose(fp); fclose(fp);
/* Use the function implemented in projecteuler.c to find the maximum path.*/ /* Use the function implemented in projecteuler.c to find the maximum path.*/
max = find_max_path(triang, 15); max = find_max_path(triang, 15);
for(i = 0; i < 15; i++) for(i = 0; i < 15; i++)
{ {
free(triang[i]); free(triang[i]);
} }
free(triang); free(triang);
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 18\n"); printf("Project Euler, Problem 18\n");
printf("Answer: %d\n", max); printf("Answer: %d\n", max);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0; return 0;
} }

126
C/p019.c
View File

@ -11,6 +11,8 @@
* *
* How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?*/ * How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <time.h> #include <time.h>
@ -20,75 +22,75 @@ typedef enum {mon, tue, wed, thu, fri, sat, sun} days;
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int year, i, limit, count = 0; int year, i, limit, count = 0;
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
months month; months month;
days day; days day;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
day = mon; day = mon;
month = jan; month = jan;
year = 1900; year = 1900;
while(year < 2001) while(year < 2001)
{ {
/* February has 29 days on leap years, otherwise 28. Leap years are those /* February has 29 days on leap years, otherwise 28. Leap years are those
* divisible by 4, but not if they're divisible by 100, except when they're * divisible by 4, but not if they're divisible by 100, except when they're
* divisible by 400.*/ * divisible by 400.*/
if(month == feb) if(month == feb)
{ {
if(year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) if(year % 400 == 0 || (year % 4 == 0 && year % 100 != 0))
{ {
limit = 29; limit = 29;
} }
else else
{ {
limit = 28; limit = 28;
} }
} }
/* April, June, September and November have 30 days.*/ /* April, June, September and November have 30 days.*/
else if(month == apr || month == jun || month == sep || month == nov) else if(month == apr || month == jun || month == sep || month == nov)
{ {
limit = 30; limit = 30;
} }
/* All other months have 31 days.*/ /* All other months have 31 days.*/
else else
{ {
limit = 31; limit = 31;
} }
/* Loop on every day of the month.*/ /* Loop on every day of the month.*/
for(i = 1; i <= limit; i++) for(i = 1; i <= limit; i++)
{ {
/* If it's the first day of the month and it's Sunday, increase /* If it's the first day of the month and it's Sunday, increase
* counter, except if year=1900 (we need to count Sundays from * counter, except if year=1900 (we need to count Sundays from
* 1901 to 2000.*/ * 1901 to 2000.*/
if(year > 1900 && i == 1 && day == sun) if(year > 1900 && i == 1 && day == sun)
{ {
count++; count++;
} }
/* Change day of the week.*/ /* Change day of the week.*/
day = (day + 1) % 7; day = (day + 1) % 7;
} }
/* At the end of the month, go to next month.*/ /* At the end of the month, go to next month.*/
month = (month + 1) % 12; month = (month + 1) % 12;
/* If we're back to january, increase the year.*/ /* If we're back to january, increase the year.*/
if(month == jan) if(month == jan)
{ {
year++; year++;
} }
} }
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 19\n"); printf("Project Euler, Problem 19\n");
printf("Answer: %d\n", count); printf("Answer: %d\n", count);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0; return 0;
} }

View File

@ -5,6 +5,8 @@
* *
* Find the sum of the digits in the number 100!*/ * Find the sum of the digits in the number 100!*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <time.h> #include <time.h>
@ -12,35 +14,35 @@
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
mpz_t fact, r, sum; mpz_t fact, r, sum;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
/* Calculate the factorial using the GMP Library and sum the digits.*/ /* Calculate the factorial using the GMP Library and sum the digits.*/
mpz_inits(fact, r, sum, NULL); mpz_inits(fact, r, sum, NULL);
mpz_fac_ui(fact, 100); mpz_fac_ui(fact, 100);
mpz_set_ui(sum, 0); mpz_set_ui(sum, 0);
while(mpz_cmp_ui(fact, 0)) while(mpz_cmp_ui(fact, 0))
{ {
mpz_tdiv_qr_ui(fact, r, fact, 10); mpz_tdiv_qr_ui(fact, r, fact, 10);
mpz_add(sum, sum, r); mpz_add(sum, sum, r);
} }
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 20\n"); printf("Project Euler, Problem 20\n");
gmp_printf("Answer: %Zd\n", sum); gmp_printf("Answer: %Zd\n", sum);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
mpz_clears(fact, r, sum, NULL); mpz_clears(fact, r, sum, NULL);
return 0; return 0;
} }

View File

@ -6,6 +6,8 @@
* *
* Evaluate the sum of all the amicable numbers under 10000.*/ * Evaluate the sum of all the amicable numbers under 10000.*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <math.h> #include <math.h>
@ -14,35 +16,35 @@
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int i, n, sum = 0; int i, n, sum = 0;
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
for(i = 2; i < 10000; i++) for(i = 2; i < 10000; i++)
{ {
/* Calculate the sum of proper divisors with the function /* Calculate the sum of proper divisors with the function
* implemented in projecteuler.c.*/ * implemented in projecteuler.c.*/
n = sum_of_divisors(i, 1); n = sum_of_divisors(i, 1);
/* If i!=n and the sum of proper divisors of n=i, /* If i!=n and the sum of proper divisors of n=i,
* sum the pair of numbers and add it to the total.*/ * sum the pair of numbers and add it to the total.*/
if(i != n && sum_of_divisors(n, 1) == i) if(i != n && sum_of_divisors(n, 1) == i)
{ {
sum += i + n; sum += i + n;
} }
} }
sum /= 2; sum /= 2;
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 21\n"); printf("Project Euler, Problem 21\n");
printf("Answer: %d\n", sum); printf("Answer: %d\n", sum);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0; return 0;
} }

120
C/p022.c
View File

@ -6,6 +6,8 @@
* *
* What is the total of all the name scores in the file?*/ * What is the total of all the name scores in the file?*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
@ -16,86 +18,86 @@ int compare(void *string1, void *string2);
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
FILE *fp; FILE *fp;
int i, j, n, len, score, sum = 0; int i, j, n, len, score, sum = 0;
double elapsed; double elapsed;
char *line, **names; char *line, **names;
struct timespec start, end; struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
if((fp = fopen("names.txt", "r")) == NULL) if((fp = fopen("names.txt", "r")) == NULL)
{ {
fprintf(stderr, "Error while opening file %s\n", "names.txt"); fprintf(stderr, "Error while opening file %s\n", "names.txt");
return 1; return 1;
} }
fscanf(fp, "%ms", &line); fscanf(fp, "%ms", &line);
fclose(fp); fclose(fp);
len = strlen(line); len = strlen(line);
n = 1; n = 1;
/* Count the names in the file.*/ /* Count the names in the file.*/
for(i = 0; i < len; i++) for(i = 0; i < len; i++)
{ {
if(line[i] == ',') if(line[i] == ',')
{ {
n++; n++;
} }
} }
if((names = (char **)malloc(n*sizeof(char *))) == NULL) if((names = (char **)malloc(n*sizeof(char *))) == NULL)
{ {
fprintf(stderr, "Error while allocating memory\n"); fprintf(stderr, "Error while allocating memory\n");
return 1; return 1;
} }
/* Save each name in a string.*/ /* Save each name in a string.*/
names[0] = strtok(line, ",\""); names[0] = strtok(line, ",\"");
for(i = 1; i < n; i++) for(i = 1; i < n; i++)
{ {
names[i] = strtok(NULL, ",\""); names[i] = strtok(NULL, ",\"");
} }
/* Use quick_sort algorithm implemented in projecteuler.c to sort the names.*/ /* Use quick_sort algorithm implemented in projecteuler.c to sort the names.*/
quick_sort((void **)names, 0, n-1, compare); quick_sort((void **)names, 0, n-1, compare);
/* Calculate the score of each name an multiply by its position.*/ /* Calculate the score of each name an multiply by its position.*/
for(i = 0; i < n; i++) for(i = 0; i < n; i++)
{ {
len = strlen(names[i]); len = strlen(names[i]);
score = 0; score = 0;
for(j = 0; j < len; j++) for(j = 0; j < len; j++)
{ {
score += names[i][j] - 'A' + 1; score += names[i][j] - 'A' + 1;
} }
score *= (i + 1); score *= (i + 1);
sum += score; sum += score;
} }
free(line); free(line);
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 22\n"); printf("Project Euler, Problem 22\n");
printf("Answer: %d\n", sum); printf("Answer: %d\n", sum);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0; return 0;
} }
/* Function to compare two strings, to pass to the quick_sort function.*/ /* Function to compare two strings, to pass to the quick_sort function.*/
int compare(void *string1, void *string2) int compare(void *string1, void *string2)
{ {
char *s1, *s2; char *s1, *s2;
s1 = (char *)string1; s1 = (char *)string1;
s2 = (char *)string2; s2 = (char *)string2;
return strcmp(s1, s2); return strcmp(s1, s2);
} }

View File

@ -10,6 +10,8 @@
* *
* Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers.*/ * Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers.*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <math.h> #include <math.h>
@ -20,69 +22,69 @@ int is_abundant(int n);
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int ab_nums[28123], sums[28123] = {0}; int ab_nums[28123], sums[28123] = {0};
int i, j, sum; int i, j, sum;
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
for(i = 0; i < 28123; i++) for(i = 0; i < 28123; i++)
{ {
/* Find all abundant numbers smaller than 28123.*/ /* Find all abundant numbers smaller than 28123.*/
ab_nums[i] = is_abundant(i+1); ab_nums[i] = is_abundant(i+1);
} }
/* For every abundant number, sum every other abundant number greater /* For every abundant number, sum every other abundant number greater
* than itself, until the sum exceeds 28123. Record that the resulting * than itself, until the sum exceeds 28123. Record that the resulting
* number is the sum of two abundant numbers.*/ * number is the sum of two abundant numbers.*/
for(i = 0; i < 28123; i++) for(i = 0; i < 28123; i++)
{ {
if(ab_nums[i]) if(ab_nums[i])
{ {
for(j = i; j < 28123; j++) for(j = i; j < 28123; j++)
{
if(ab_nums[j])
{ {
sum = i + j + 2; if(ab_nums[j])
{
sum = i + j + 2;
if(sum <= 28123) if(sum <= 28123)
{ {
sums[sum-1] = 1; sums[sum-1] = 1;
} }
else else
{ {
break; break;
} }
}
} }
} }
} }
}
sum = 0; sum = 0;
/* Sum every number that was not found as a sum of two abundant numbers.*/ /* Sum every number that was not found as a sum of two abundant numbers.*/
for(i = 0; i < 28123; i++) for(i = 0; i < 28123; i++)
{ {
if(!sums[i]) if(!sums[i])
{ {
sum += i + 1; sum += i + 1;
} }
} }
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 23\n"); printf("Project Euler, Problem 23\n");
printf("Answer: %d\n", sum); printf("Answer: %d\n", sum);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0; return 0;
} }
int is_abundant(int n) int is_abundant(int n)
{ {
return sum_of_divisors(n, 1) > n; return sum_of_divisors(n, 1) > n;
} }

View File

@ -5,6 +5,8 @@
* *
* What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9?*/ * What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9?*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <time.h> #include <time.h>
@ -14,69 +16,69 @@ int compare(void *a, void *b);
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int i, res[10]; int i, res[10];
int **perm; int **perm;
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
if((perm = (int **)malloc(10*sizeof(int *))) == NULL) if((perm = (int **)malloc(10*sizeof(int *))) == NULL)
{ {
fprintf(stderr, "Error while allocating memory\n"); fprintf(stderr, "Error while allocating memory\n");
return 1; return 1;
} }
for(i = 0; i < 10; i++) for(i = 0; i < 10; i++)
{ {
if((perm[i] = (int *)malloc(sizeof(int))) == NULL) if((perm[i] = (int *)malloc(sizeof(int))) == NULL)
{ {
fprintf(stderr, "Error while allocating memory\n"); fprintf(stderr, "Error while allocating memory\n");
return 1; return 1;
} }
*perm[i] = i; *perm[i] = i;
} }
for(i = 0; i < 999999; i++) for(i = 0; i < 999999; i++)
{ {
/* Function that generates permutations in lexicographic order. /* Function that generates permutations in lexicographic order.
* Finish when the 1000000th is found.*/ * Finish when the 1000000th is found.*/
next_permutation((void **)perm, 10, compare); next_permutation((void **)perm, 10, compare);
} }
for(i = 0; i < 10; i++) for(i = 0; i < 10; i++)
{ {
res[i] = *perm[i]; res[i] = *perm[i];
free(perm[i]); free(perm[i]);
} }
free(perm); free(perm);
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
printf("Project Euler, Problem 24\n"); printf("Project Euler, Problem 24\n");
printf("Answer: "); printf("Answer: ");
for(i = 0; i < 10; i++) for(i = 0; i < 10; i++)
{ {
printf("%d", res[i]); printf("%d", res[i]);
} }
printf("\n"); printf("\n");
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0; return 0;
} }
int compare(void *a, void *b) int compare(void *a, void *b)
{ {
int *n1, *n2; int *n1, *n2;
n1 = (int *)a; n1 = (int *)a;
n2 = (int *)b; n2 = (int *)b;
return *n1 - *n2; return *n1 - *n2;
} }

View File

@ -19,6 +19,8 @@
* *
* What is the index of the first term in the Fibonacci sequence to contain 1000 digits?*/ * What is the index of the first term in the Fibonacci sequence to contain 1000 digits?*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
@ -27,61 +29,61 @@
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int i; int i;
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
mpz_t f1, f2, fn; mpz_t f1, f2, fn;
char *num; char *num;
size_t size; size_t size;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
mpz_init_set_ui(f1, 1); mpz_init_set_ui(f1, 1);
mpz_init_set_ui(f2, 1); mpz_init_set_ui(f2, 1);
mpz_init(fn); mpz_init(fn);
i = 2; i = 2;
while(1) while(1)
{ {
/* Use the GMP Library to calculate the Fibonacci numbers.*/ /* Use the GMP Library to calculate the Fibonacci numbers.*/
mpz_add(fn, f1, f2); mpz_add(fn, f1, f2);
i++; i++;
/* The function mpz_sizeinbase gives the number of digits of /* The function mpz_sizeinbase gives the number of digits of
* the number in the given base, but the result is either exact * the number in the given base, but the result is either exact
* or one too big. To check the exact size, the number is * or one too big. To check the exact size, the number is
* converted to string and the strlen function is used.*/ * converted to string and the strlen function is used.*/
if((size = mpz_sizeinbase(fn, 10)) >= 1000) if((size = mpz_sizeinbase(fn, 10)) >= 1000)
{ {
if((num = (char *)malloc((2+size)*sizeof(char))) == NULL) if((num = (char *)malloc((2+size)*sizeof(char))) == NULL)
{ {
fprintf(stderr, "Error while allocating memory\n"); fprintf(stderr, "Error while allocating memory\n");
return 1; return 1;
} }
gmp_sprintf(num, "%Zd", fn); gmp_sprintf(num, "%Zd", fn);
size = strlen(num); size = strlen(num);
free(num); free(num);
if(size == 1000) if(size == 1000)
{ {
break; break;
} }
} }
mpz_set(f1, f2); mpz_set(f1, f2);
mpz_set(f2, fn); mpz_set(f2, fn);
} }
mpz_clears(f1, f2, fn, NULL); mpz_clears(f1, f2, fn, NULL);
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 25\n"); printf("Project Euler, Problem 25\n");
printf("Answer: %d\n", i); printf("Answer: %d\n", i);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0; return 0;
} }

100
C/p026.c
View File

@ -14,6 +14,8 @@
* *
* Find the value of d < 1000 for which 1/d contains the longest recurring cycle in its decimal fraction part.*/ * Find the value of d < 1000 for which 1/d contains the longest recurring cycle in its decimal fraction part.*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <math.h> #include <math.h>
@ -22,67 +24,67 @@
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int i, j, n, max = 0, max_n = 0; int i, j, n, max = 0, max_n = 0;
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
mpz_t k, div; mpz_t k, div;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
mpz_init(k); mpz_init(k);
mpz_init(div); mpz_init(div);
for(i = 2; i < 1000; i++) for(i = 2; i < 1000; i++)
{ {
j = i; j = i;
/* The repeating cycle of 1/(2^a*5^b*p^c*...) is equal to /* The repeating cycle of 1/(2^a*5^b*p^c*...) is equal to
* that of 1/p^c*..., so factors 2 and 5 can be eliminated.*/ * that of 1/p^c*..., so factors 2 and 5 can be eliminated.*/
while(j % 2 == 0 && j > 1) while(j % 2 == 0 && j > 1)
j /= 2; j /= 2;
while(j % 5 == 0 && j > 1) while(j % 5 == 0 && j > 1)
j /= 5; j /= 5;
/* If the denominator had only factors 2 and 5, there is no /* If the denominator had only factors 2 and 5, there is no
* repeating cycle.*/ * repeating cycle.*/
if(j == 1) if(j == 1)
n = 0; n = 0;
else else
{ {
n = 1; n = 1;
mpz_set_ui(k, 9); mpz_set_ui(k, 9);
mpz_set_ui(div, j); mpz_set_ui(div, j);
/* After eliminating factors 2s and 5s, the length of the repeating cycle /* After eliminating factors 2s and 5s, the length of the repeating cycle
* of 1/d is the smallest n for which k=10^n-1/d is an integer. So we start * of 1/d is the smallest n for which k=10^n-1/d is an integer. So we start
* with k=9, then k=99, k=999 and so on until k is divisible by d. * with k=9, then k=99, k=999 and so on until k is divisible by d.
* The number of digits of k is the length of the repeating cycle.*/ * The number of digits of k is the length of the repeating cycle.*/
while(!mpz_divisible_p(k, div)) while(!mpz_divisible_p(k, div))
{ {
n++; n++;
mpz_mul_ui(k, k, 10); mpz_mul_ui(k, k, 10);
mpz_add_ui(k, k, 9); mpz_add_ui(k, k, 9);
} }
if(n > max) if(n > max)
{ {
max = n; max = n;
max_n = i; max_n = i;
} }
} }
} }
mpz_clears(k, div, NULL); mpz_clears(k, div, NULL);
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 26\n"); printf("Project Euler, Problem 26\n");
printf("Answer: %d\n", max_n); printf("Answer: %d\n", max_n);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0; return 0;
} }

View File

@ -17,6 +17,8 @@
* *
* Find the product of the coefficients, a and b, for the quadratic expression that produces the maximum number of primes for consecutive values of n, starting with n=0.*/ * Find the product of the coefficients, a and b, for the quadratic expression that produces the maximum number of primes for consecutive values of n, starting with n=0.*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <math.h> #include <math.h>
@ -25,56 +27,56 @@
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int a, b, n, p, count, max = 0, save_a, save_b; int a, b, n, p, count, max = 0, save_a, save_b;
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
/* Brute force approach, optimized by checking only values of b where b is prime.*/ /* Brute force approach, optimized by checking only values of b where b is prime.*/
for(a = -999; a < 1000; a++) for(a = -999; a < 1000; a++)
{ {
for(b = 2; b <= 1000; b++) for(b = 2; b <= 1000; b++)
{ {
/* For n=0, n^2+an+b=b, so b must be prime.*/ /* For n=0, n^2+an+b=b, so b must be prime.*/
if(is_prime(b)) if(is_prime(b))
{
n = 0;
count = 0;
while(1)
{ {
p = n * n + a * n + b; n = 0;
count = 0;
if(p > 1 && is_prime(p)) while(1)
{ {
count++; p = n * n + a * n + b;
n++;
} if(p > 1 && is_prime(p))
else {
{ count++;
break; n++;
} }
else
{
break;
}
}
if(count > max)
{
max = count;
save_a = a;
save_b = b;
}
} }
}
}
if(count > max) clock_gettime(CLOCK_MONOTONIC, &end);
{
max = count;
save_a = a;
save_b = b;
}
}
}
}
clock_gettime(CLOCK_MONOTONIC, &end); elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; printf("Project Euler, Problem 27\n");
printf("Answer: %d\n", save_a * save_b);
printf("Project Euler, Problem 27\n"); printf("Elapsed time: %.9lf seconds\n", elapsed);
printf("Answer: %d\n", save_a * save_b);
printf("Elapsed time: %.9lf seconds\n", elapsed); return 0;
return 0;
} }

View File

@ -10,6 +10,8 @@
* *
* What is the sum of the numbers on the diagonals in a 1001 by 1001 spiral formed in the same way?*/ * What is the sum of the numbers on the diagonals in a 1001 by 1001 spiral formed in the same way?*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <time.h> #include <time.h>
@ -18,35 +20,35 @@
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int i, j, step = 0, limit = N * N, sum = 1; int i, j, step = 0, limit = N * N, sum = 1;
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
/* Starting with the central 1, it's easy to see that the next four numbers in the diagonal /* Starting with the central 1, it's easy to see that the next four numbers in the diagonal
* are 1+2, 1+2+2, 1+2+2+2 and 1+2+2+2+2, then for the next four number the step is increased * are 1+2, 1+2+2, 1+2+2+2 and 1+2+2+2+2, then for the next four number the step is increased
* by two, so from 9 to 9+4, 9+4+4 etc, for the next four number the step is again increased * by two, so from 9 to 9+4, 9+4+4 etc, for the next four number the step is again increased
* by two, and so on. We go on until the value is equal to N*N, with N=1001 for this problem.*/ * by two, and so on. We go on until the value is equal to N*N, with N=1001 for this problem.*/
for(i = 0, j = 1; j < limit; i = (i + 1) % 4) for(i = 0, j = 1; j < limit; i = (i + 1) % 4)
{ {
if(i == 0) if(i == 0)
{ {
step += 2; step += 2;
} }
j += step; j += step;
sum += j; sum += j;
} }
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 28\n"); printf("Project Euler, Problem 28\n");
printf("Answer: %d\n", sum); printf("Answer: %d\n", sum);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0; return 0;
} }

122
C/p029.c
View File

@ -11,6 +11,8 @@
* *
* How many distinct terms are in the sequence generated by ab for 2 a 100 and 2 b 100?*/ * How many distinct terms are in the sequence generated by ab for 2 a 100 and 2 b 100?*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <time.h> #include <time.h>
@ -21,86 +23,86 @@ int compare(void *a, void *b);
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
mpz_t a; mpz_t a;
mpz_t **powers; mpz_t **powers;
int i, j, count; int i, j, count;
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
if((powers = (mpz_t **)malloc(9801*sizeof(mpz_t *))) == NULL) if((powers = (mpz_t **)malloc(9801*sizeof(mpz_t *))) == NULL)
{ {
fprintf(stderr, "Error while allocating memory\n"); fprintf(stderr, "Error while allocating memory\n");
return 1; return 1;
} }
for(i = 0; i < 9801; i++) for(i = 0; i < 9801; i++)
{ {
if((powers[i] = (mpz_t *)malloc(sizeof(mpz_t))) == NULL) if((powers[i] = (mpz_t *)malloc(sizeof(mpz_t))) == NULL)
{ {
fprintf(stderr, "Error while allocating memory\n"); fprintf(stderr, "Error while allocating memory\n");
return 1; return 1;
} }
} }
mpz_init(a); mpz_init(a);
for(i = 0; i < 9801; i++) for(i = 0; i < 9801; i++)
{ {
mpz_init(*powers[i]); mpz_init(*powers[i]);
} }
/* Using the GMP Library to calculate all the powers.*/ /* Using the GMP Library to calculate all the powers.*/
for(i = 2; i <= 100; i++) for(i = 2; i <= 100; i++)
{ {
mpz_set_ui(a, i); mpz_set_ui(a, i);
for(j = 2; j <= 100; j++) for(j = 2; j <= 100; j++)
{ {
mpz_pow_ui(*powers[(i-2)*99+j-2], a, j); mpz_pow_ui(*powers[(i-2)*99+j-2], a, j);
} }
} }
mpz_clear(a); mpz_clear(a);
/* Sort the values and count the different values.*/ /* Sort the values and count the different values.*/
quick_sort((void **)powers, 0, 9800, compare); quick_sort((void **)powers, 0, 9800, compare);
count = 1; count = 1;
for(i = 1; i < 9801; i++) for(i = 1; i < 9801; i++)
{ {
if(mpz_cmp(*powers[i], *powers[i-1])) if(mpz_cmp(*powers[i], *powers[i-1]))
{ {
count++; count++;
} }
} }
for(i = 0; i < 9801; i++) for(i = 0; i < 9801; i++)
{ {
mpz_clear(*powers[i]); mpz_clear(*powers[i]);
free(powers[i]); free(powers[i]);
} }
free(powers); free(powers);
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 29\n"); printf("Project Euler, Problem 29\n");
printf("Answer: %d\n", count); printf("Answer: %d\n", count);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0; return 0;
} }
int compare(void *a, void *b) int compare(void *a, void *b)
{ {
mpz_t *n1, *n2; mpz_t *n1, *n2;
n1 = (mpz_t *)a; n1 = (mpz_t *)a;
n2 = (mpz_t *)b; n2 = (mpz_t *)b;
return mpz_cmp(*n1, *n2); return mpz_cmp(*n1, *n2);
} }

View File

@ -10,6 +10,8 @@
* *
* Find the sum of all the numbers that can be written as the sum of fifth powers of their digits.*/ * Find the sum of all the numbers that can be written as the sum of fifth powers of their digits.*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <math.h> #include <math.h>
@ -17,41 +19,41 @@
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int i, j, digit, sum, sum_tot = 0; int i, j, digit, sum, sum_tot = 0;
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
/* Straightforward brute force approach. The limit is chosen considering that /* Straightforward brute force approach. The limit is chosen considering that
* 6*9^5=354294, so no number larger than that can be expressed as sum * 6*9^5=354294, so no number larger than that can be expressed as sum
* of 5th power of its digits.*/ * of 5th power of its digits.*/
for(i = 10; i < 354295; i++) for(i = 10; i < 354295; i++)
{ {
j = i; j = i;
sum = 0; sum = 0;
while(j > 0) while(j > 0)
{ {
digit = j % 10; digit = j % 10;
sum += (pow(digit, 5)); sum += (pow(digit, 5));
j /= 10; j /= 10;
} }
if(sum == i) if(sum == i)
{ {
sum_tot += i; sum_tot += i;
} }
} }
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed=(end.tv_sec-start.tv_sec)+(double)(end.tv_nsec-start.tv_nsec)/1000000000; elapsed=(end.tv_sec-start.tv_sec)+(double)(end.tv_nsec-start.tv_nsec)/1000000000;
printf("Project Euler, problem 30\n"); printf("Project Euler, problem 30\n");
printf("Answer: %d\n", sum_tot); printf("Answer: %d\n", sum_tot);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0; return 0;
} }

View File

@ -8,6 +8,8 @@
* *
* How many different ways can £2 be made using any number of coins?*/ * How many different ways can £2 be made using any number of coins?*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <time.h> #include <time.h>
@ -18,49 +20,49 @@ int coins[8] = {1, 2, 5, 10, 20, 50, 100, 200};
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int n; int n;
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
n = count(0, 0, 0); n = count(0, 0, 0);
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 31\n"); printf("Project Euler, Problem 31\n");
printf("Answer: %d\n", n); printf("Answer: %d\n", n);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0; return 0;
} }
/* Simple recursive function that tries every combination.*/ /* Simple recursive function that tries every combination.*/
int count(int value, int n, int i) int count(int value, int n, int i)
{ {
int j; int j;
for(j = i; j < 8; j++) for(j = i; j < 8; j++)
{ {
value += coins[j]; value += coins[j];
if(value == 200) if(value == 200)
{ {
return n + 1; return n + 1;
} }
else if(value > 200) else if(value > 200)
{ {
return n; return n;
} }
else else
{ {
n = count(value, n, j); n = count(value, n, j);
value -= coins[j]; value -= coins[j];
} }
} }
return n; return n;
} }

198
C/p032.c
View File

@ -7,6 +7,8 @@
* *
* HINT: Some products can be obtained in more than one way so be sure to only include it once in your sum.*/ * HINT: Some products can be obtained in more than one way so be sure to only include it once in your sum.*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
@ -17,129 +19,129 @@ int compare(void *a, void *b);
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int i, j, p, sum, n = 0, num; int i, j, p, sum, n = 0, num;
int **products; int **products;
char num_s[10]; char num_s[10];
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
/* Initially I used a bigger array, but printing the resulting products /* Initially I used a bigger array, but printing the resulting products
* shows that 10 values are sufficient.*/ * shows that 10 values are sufficient.*/
if((products = (int **)malloc(10*sizeof(int *))) == NULL) if((products = (int **)malloc(10*sizeof(int *))) == NULL)
{ {
fprintf(stderr, "Error while allocating memory\n"); fprintf(stderr, "Error while allocating memory\n");
return 1; return 1;
} }
for(i = 0; i < 10; i++) for(i = 0; i < 10; i++)
{ {
if((products[i] = (int *)malloc(sizeof(int))) == NULL) if((products[i] = (int *)malloc(sizeof(int))) == NULL)
{ {
fprintf(stderr, "Error while allocating memory\n"); fprintf(stderr, "Error while allocating memory\n");
return 1; return 1;
} }
} }
/* To get a 1 to 9 pandigital concatenation of the two factors and product, /* To get a 1 to 9 pandigital concatenation of the two factors and product,
* we need to multiply a 1 digit number times a 4 digit numbers (the biggest * we need to multiply a 1 digit number times a 4 digit numbers (the biggest
* one digit number 9 times the biggest 3 digit number 999 multiplied give * one digit number 9 times the biggest 3 digit number 999 multiplied give
* 8991 and the total digit count is 8, which is not enough), or a 2 digit * 8991 and the total digit count is 8, which is not enough), or a 2 digit
* number times a 3 digit number (the smallest two different 3 digits number, * number times a 3 digit number (the smallest two different 3 digits number,
* 100 and 101, multiplied give 10100, and the total digit count is 11, which * 100 and 101, multiplied give 10100, and the total digit count is 11, which
* is too many). The outer loop starts at 2 because 1 times any number gives * is too many). The outer loop starts at 2 because 1 times any number gives
* the same number, so its digit will be repeated and the result can't be * the same number, so its digit will be repeated and the result can't be
* pandigital. The nested loop starts from 1234 because it's the smallest * pandigital. The nested loop starts from 1234 because it's the smallest
* 4-digit number with no repeated digits, and it ends at 4987 because it's * 4-digit number with no repeated digits, and it ends at 4987 because it's
* the biggest number without repeated digits that multiplied by 2 gives a * the biggest number without repeated digits that multiplied by 2 gives a
* 4 digit number. */ * 4 digit number. */
for(i = 2; i < 9; i++) for(i = 2; i < 9; i++)
{ {
for(j = 1234; j < 4987; j++) for(j = 1234; j < 4987; j++)
{ {
p = i * j; p = i * j;
sprintf(num_s, "%d%d%d", i, j, p); sprintf(num_s, "%d%d%d", i, j, p);
if(strlen(num_s) > 9) if(strlen(num_s) > 9)
{ {
break; break;
} }
num = atoi(num_s); num = atoi(num_s);
if(is_pandigital(num, 9)) if(is_pandigital(num, 9))
{ {
*products[n] = p; *products[n] = p;
n++; n++;
} }
} }
} }
/* The outer loop starts at 12 because 10 has a 0 and 11 has two 1s, so /* The outer loop starts at 12 because 10 has a 0 and 11 has two 1s, so
* the result can't be pandigital. The nested loop starts at 123 because * the result can't be pandigital. The nested loop starts at 123 because
* it's the smallest 3-digit number with no digit repetitions and ends at * it's the smallest 3-digit number with no digit repetitions and ends at
* 833, because 834*12 has 5 digits.*/ * 833, because 834*12 has 5 digits.*/
for(i = 12; i < 99; i++) for(i = 12; i < 99; i++)
{ {
for(j = 123; j < 834; j++) for(j = 123; j < 834; j++)
{ {
p = i * j; p = i * j;
sprintf(num_s, "%d%d%d", i, j, p); sprintf(num_s, "%d%d%d", i, j, p);
if(strlen(num_s) > 9) if(strlen(num_s) > 9)
{ {
break; break;
} }
num = atoi(num_s); num = atoi(num_s);
if(is_pandigital(num, 9)) if(is_pandigital(num, 9))
{ {
*products[n] = p; *products[n] = p;
n++; n++;
} }
} }
} }
/* Sort the found products to easily see if there are duplicates.*/ /* Sort the found products to easily see if there are duplicates.*/
insertion_sort((void **)products, 0, n-1, compare); insertion_sort((void **)products, 0, n-1, compare);
sum = *products[0]; sum = *products[0];
for(i = 1; i < n; i++) for(i = 1; i < n; i++)
{ {
if(*products[i] != *products[i-1]) if(*products[i] != *products[i-1])
{ {
sum += *products[i]; sum += *products[i];
} }
} }
for(i = 0; i < 10; i++) for(i = 0; i < 10; i++)
{ {
free(products[i]); free(products[i]);
} }
free(products); free(products);
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 32\n"); printf("Project Euler, Problem 32\n");
printf("Answer: %d\n", sum); printf("Answer: %d\n", sum);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0; return 0;
} }
int compare(void *a, void *b) int compare(void *a, void *b)
{ {
int *n1, *n2; int *n1, *n2;
n1 = (int *)a; n1 = (int *)a;
n2 = (int *)b; n2 = (int *)b;
return *n1 - *n2; return *n1 - *n2;
} }

View File

@ -8,6 +8,8 @@
* *
* If the product of these four fractions is given in its lowest common terms, find the value of the denominator.*/ * If the product of these four fractions is given in its lowest common terms, find the value of the denominator.*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <time.h> #include <time.h>
@ -15,47 +17,47 @@
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int i, j, n, d, prod_n = 1, prod_d = 1, div; int i, j, n, d, prod_n = 1, prod_d = 1, div;
float f1, f2; float f1, f2;
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
for(i = 11; i < 100; i++) for(i = 11; i < 100; i++)
{ {
for(j = 11; j < 100; j++) for(j = 11; j < 100; j++)
{ {
/* If the example is non-trivial, check if cancelling the digit that's equal /* If the example is non-trivial, check if cancelling the digit that's equal
* in numerator and denominator gives the same fraction.*/ * in numerator and denominator gives the same fraction.*/
if(i % 10 && j % 10 && i != j && i % 10 == j / 10) if(i % 10 && j % 10 && i != j && i % 10 == j / 10)
{
n = i / 10;
d = j % 10;
f1 = (float)i / j;
f2 = (float)n / d;
if(f1 == f2)
{ {
prod_n *= i; n = i / 10;
prod_d *= j; d = j % 10;
f1 = (float)i / j;
f2 = (float)n / d;
if(f1 == f2)
{
prod_n *= i;
prod_d *= j;
}
} }
} }
} }
}
/* Find the greater common divisor of the fraction found.*/ /* Find the greater common divisor of the fraction found.*/
div = gcd(prod_n, prod_d); div = gcd(prod_n, prod_d);
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 33\n"); printf("Project Euler, Problem 33\n");
printf("Answer: %d\n", prod_d/div); printf("Answer: %d\n", prod_d/div);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0; return 0;
} }

View File

@ -4,6 +4,8 @@
* *
* Note: as 1! = 1 and 2! = 2 are not sums they are not included.*/ * Note: as 1! = 1 and 2! = 2 are not sums they are not included.*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <time.h> #include <time.h>
@ -11,66 +13,66 @@
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int i; int i;
unsigned long int digit; unsigned long int digit;
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
mpz_t a, b, q, sum_f, sum, factorials[10]; mpz_t a, b, q, sum_f, sum, factorials[10];
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
mpz_init_set_ui(a, 10); mpz_init_set_ui(a, 10);
mpz_init_set_ui(sum, 0); mpz_init_set_ui(sum, 0);
mpz_inits(b, q, sum_f, sum, NULL); mpz_inits(b, q, sum_f, sum, NULL);
for(i = 0; i < 10; i++) for(i = 0; i < 10; i++)
{ {
mpz_init_set_ui(factorials[i], 1); mpz_init_set_ui(factorials[i], 1);
} }
/* Pre-calculate factorials of each digit from 0 to 9.*/ /* Pre-calculate factorials of each digit from 0 to 9.*/
for(i = 2; i < 10; i++) for(i = 2; i < 10; i++)
{ {
mpz_fac_ui(factorials[i], i); mpz_fac_ui(factorials[i], i);
} }
/* 9!*7<9999999, so 9999999 is certainly un upper bound.*/ /* 9!*7<9999999, so 9999999 is certainly un upper bound.*/
while(mpz_cmp_ui(a, 9999999) < 0) while(mpz_cmp_ui(a, 9999999) < 0)
{ {
mpz_set(b, a); mpz_set(b, a);
mpz_set_ui(sum_f, 0); mpz_set_ui(sum_f, 0);
while(mpz_cmp_ui(b, 0)) while(mpz_cmp_ui(b, 0))
{ {
digit = mpz_fdiv_qr_ui(b, q, b, 10); digit = mpz_fdiv_qr_ui(b, q, b, 10);
mpz_add(sum_f, sum_f, factorials[digit]); mpz_add(sum_f, sum_f, factorials[digit]);
} }
if(!mpz_cmp(a, sum_f)) if(!mpz_cmp(a, sum_f))
{ {
mpz_add(sum, sum, a); mpz_add(sum, sum, a);
} }
mpz_add_ui(a, a, 1); mpz_add_ui(a, a, 1);
} }
mpz_clears(a, b, q, sum_f, NULL); mpz_clears(a, b, q, sum_f, NULL);
for(i = 0; i < 10; i++) for(i = 0; i < 10; i++)
{ {
mpz_clear(factorials[i]); mpz_clear(factorials[i]);
} }
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 34\n"); printf("Project Euler, Problem 34\n");
gmp_printf("Answer: %Zd\n", sum); gmp_printf("Answer: %Zd\n", sum);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
mpz_clear(sum); mpz_clear(sum);
return 0; return 0;
} }

122
C/p035.c
View File

@ -4,6 +4,8 @@
* *
* How many circular primes are there below one million?*/ * How many circular primes are there below one million?*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <math.h> #include <math.h>
@ -18,83 +20,83 @@ int *primes;
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int i, count = 13; int i, count = 13;
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
/* Calculate all primes below one million, then check if they're circular.*/ /* Calculate all primes below one million, then check if they're circular.*/
if((primes = sieve(N)) == NULL) if((primes = sieve(N)) == NULL)
{ {
fprintf(stderr, "Error! Sieve function returned NULL\n"); fprintf(stderr, "Error! Sieve function returned NULL\n");
return 1; return 1;
} }
/* Starting from 101 because we already know that there are 13 circular primes below 100.*/ /* Starting from 101 because we already know that there are 13 circular primes below 100.*/
for(i = 101; i < 1000000; i += 2) for(i = 101; i < 1000000; i += 2)
{ {
if(is_circular_prime(i)) if(is_circular_prime(i))
{ {
count++; count++;
} }
} }
free(primes); free(primes);
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 35\n"); printf("Project Euler, Problem 35\n");
printf("Answer: %d\n", count); printf("Answer: %d\n", count);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0; return 0;
} }
int is_circular_prime(int n) int is_circular_prime(int n)
{ {
int i, tmp, count; int i, tmp, count;
/* If n is not prime, it's obviously not a circular prime.*/ /* If n is not prime, it's obviously not a circular prime.*/
if(primes[n] == 0) if(primes[n] == 0)
{ {
return 0; return 0;
} }
/* The primes below 10 are circular primes.*/ /* The primes below 10 are circular primes.*/
if(primes[n] == 1 && n < 10) if(primes[n] == 1 && n < 10)
{ {
return 1; return 1;
} }
tmp = n; tmp = n;
count = 0; count = 0;
while(tmp > 0) while(tmp > 0)
{ {
/* If the number has one or more even digits, it can't be a circular prime. /* If the number has one or more even digits, it can't be a circular prime.
* because at least one of the rotations will be even.*/ * because at least one of the rotations will be even.*/
if(tmp % 2 == 0) if(tmp % 2 == 0)
{ {
return 0; return 0;
} }
/* Count the number of digits.*/ /* Count the number of digits.*/
count++; count++;
tmp /= 10; tmp /= 10;
} }
for(i = 1; i < count; i++) for(i = 1; i < count; i++)
{ {
/* Generate rotations and check if they're prime.*/ /* Generate rotations and check if they're prime.*/
n = n % (int)pow(10, count-1) * 10 + n / (int)pow(10, count-1); n = n % (int)pow(10, count-1) * 10 + n / (int)pow(10, count-1);
if(primes[n] == 0) if(primes[n] == 0)
{ {
return 0; return 0;
} }
} }
return 1; return 1;
} }

View File

@ -4,6 +4,8 @@
* *
* (Please note that the palindromic number, in either base, may not include leading zeros.)*/ * (Please note that the palindromic number, in either base, may not include leading zeros.)*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <time.h> #include <time.h>
@ -13,31 +15,31 @@
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int i, sum = 0; int i, sum = 0;
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
/* Brute force approach. For every number below 1 million, /* Brute force approach. For every number below 1 million,
* check if they're palindrome in base 2 and 10 using the * check if they're palindrome in base 2 and 10 using the
* function implemented in projecteuler.c.*/ * function implemented in projecteuler.c.*/
for(i = 1; i < N; i += 2) for(i = 1; i < N; i += 2)
{ {
if(is_palindrome(i, 10) && is_palindrome(i, 2)) if(is_palindrome(i, 10) && is_palindrome(i, 2))
{ {
sum += i; sum += i;
} }
} }
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 36\n"); printf("Project Euler, Problem 36\n");
printf("Answer: %d\n", sum); printf("Answer: %d\n", sum);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0; return 0;
} }

110
C/p037.c
View File

@ -5,6 +5,8 @@
* *
* NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes.*/ * NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes.*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <math.h> #include <math.h>
@ -15,75 +17,75 @@ int is_tr_prime(int n);
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int i = 0, n = 1, sum = 0; int i = 0, n = 1, sum = 0;
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
/* Check every number until 11 truncatable primes are found.*/ /* Check every number until 11 truncatable primes are found.*/
while(i < 11) while(i < 11)
{ {
if(is_tr_prime(n)) if(is_tr_prime(n))
{ {
sum += n; sum += n;
i++; i++;
} }
n++; n++;
} }
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 37\n"); printf("Project Euler, Problem 37\n");
printf("Answer: %d\n", sum); printf("Answer: %d\n", sum);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0; return 0;
} }
int is_tr_prime(int n) int is_tr_prime(int n)
{ {
int i, tmp; int i, tmp;
/* One-digit numbers and non-prime numbers are /* One-digit numbers and non-prime numbers are
* not truncatable primes.*/ * not truncatable primes.*/
if(n < 11 || !is_prime(n)) if(n < 11 || !is_prime(n))
{ {
return 0; return 0;
} }
/* Remove one digit at a time from the right and check /* Remove one digit at a time from the right and check
* if the resulting number is prime. Return 0 if it isn't.*/ * if the resulting number is prime. Return 0 if it isn't.*/
tmp = n / 10; tmp = n / 10;
while(tmp > 0) while(tmp > 0)
{ {
if(!is_prime(tmp)) if(!is_prime(tmp))
{ {
return 0; return 0;
} }
tmp /= 10; tmp /= 10;
} }
/* Starting from the last digit, check if it's prime, then /* Starting from the last digit, check if it's prime, then
* add back one digit at a time on the left and check if it * add back one digit at a time on the left and check if it
* is prime. Return 0 when it isn't.*/ * is prime. Return 0 when it isn't.*/
i = 10; i = 10;
tmp = n % i; tmp = n % i;
while(tmp != n) while(tmp != n)
{ {
if(!is_prime(tmp)) if(!is_prime(tmp))
{ {
return 0; return 0;
} }
i *= 10; i *= 10;
tmp = n % i; tmp = n % i;
} }
/* If it gets here, the number is truncatable prime.*/ /* If it gets here, the number is truncatable prime.*/
return 1; return 1;
} }

106
C/p038.c
View File

@ -11,6 +11,8 @@
* *
* What is the largest 1 to 9 pandigital 9-digit number that can be formed as the concatenated product of an integer with (1,2, ... , n) where n > 1?*/ * What is the largest 1 to 9 pandigital 9-digit number that can be formed as the concatenated product of an integer with (1,2, ... , n) where n > 1?*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <time.h> #include <time.h>
@ -18,64 +20,64 @@
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int i, j, tmp; int i, j, tmp;
long int n, max = 0; long int n, max = 0;
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
/* A brute force approach is used, starting with 1 and multiplying /* A brute force approach is used, starting with 1 and multiplying
* the number by 1, 2 etc., concatenating the results, checking if * the number by 1, 2 etc., concatenating the results, checking if
* it's 1 to 9 pandigital, and going to the next number when the * it's 1 to 9 pandigital, and going to the next number when the
* concatenated result is greater than the greatest 9 digit pandigital * concatenated result is greater than the greatest 9 digit pandigital
* value. The limit is set to 10000, since 1*10000=10000, 2*10000=20000 and * value. The limit is set to 10000, since 1*10000=10000, 2*10000=20000 and
* concatenating this two numbers a 10-digit number is obtained.*/ * concatenating this two numbers a 10-digit number is obtained.*/
for(i = 1; i < 10000; i++) for(i = 1; i < 10000; i++)
{ {
n = 0; n = 0;
j = 1; j = 1;
do do
{ {
tmp = i * j; tmp = i * j;
n += tmp; n += tmp;
j++; j++;
if(n > max && is_pandigital(n, 9)) if(n > max && is_pandigital(n, 9))
{ {
max = n; max = n;
} }
if(i * j < 10) if(i * j < 10)
{ {
n *= 10; n *= 10;
} }
else if(i * j < 100) else if(i * j < 100)
{ {
n *= 100; n *= 100;
} }
else if(i * j < 1000) else if(i * j < 1000)
{ {
n *= 1000; n *= 1000;
} }
else if(i * j < 10000) else if(i * j < 10000)
{ {
n *= 10000; n *= 10000;
} }
else if(i * j < 100000) else if(i * j < 100000)
{ {
n *= 100000; n *= 100000;
} }
}while(n <= 987654321); } while(n <= 987654321);
} }
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 38\n"); printf("Project Euler, Problem 38\n");
printf("Answer: %ld\n", max); printf("Answer: %ld\n", max);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0; return 0;
} }

134
C/p039.c
View File

@ -4,87 +4,89 @@
* *
* For which value of p 1000, is the number of solutions maximised?*/ * For which value of p 1000, is the number of solutions maximised?*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <time.h> #include <time.h>
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int p, m, n, a, b, c, count, max = 0, res = 0, tmpa, tmpb, tmpc, i; int p, m, n, a, b, c, count, max = 0, res = 0, tmpa, tmpb, tmpc, i;
int savedc[1000] = {0}; int savedc[1000] = {0};
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
/* Start with p=12 (the smallest pythagorean triplet is (3,4,5) and 3+4+5=12.*/ /* Start with p=12 (the smallest pythagorean triplet is (3,4,5) and 3+4+5=12.*/
for(p = 12; p <= 1000; p++) for(p = 12; p <= 1000; p++)
{ {
count = 0; count = 0;
a = 0; a = 0;
b = 0; b = 0;
c = 0; c = 0;
/* Generate pythagorean triplets.*/ /* Generate pythagorean triplets.*/
for(m = 2; m * m < p; m++) for(m = 2; m * m < p; m++)
{ {
for(n = 1; n < m; n++) for(n = 1; n < m; n++)
{
a = m * m - n * n;
b = 2 * m * n;
c = m * m + n * n;
/* Increase counter if a+b+c=p and the triplet is new,
* then save the value of c to avoid counting the same
* triplet more than once.*/
if(a + b + c == p && !savedc[c])
{ {
savedc[c] = 1; a = m * m - n * n;
count++; b = 2 * m * n;
c = m * m + n * n;
/* Increase counter if a+b+c=p and the triplet is new,
* then save the value of c to avoid counting the same
* triplet more than once.*/
if(a + b + c == p && !savedc[c])
{
savedc[c] = 1;
count++;
}
i = 2;
tmpa = a;
tmpb = b;
tmpc = c;
/* Check all the triplets obtained multiplying a, b and c
* for integer numbers, until the perimeters exceeds p.*/
while(tmpa + tmpb + tmpc < p)
{
tmpa = a * i;
tmpb = b * i;
tmpc = c * i;
/* Increase counter if the new a, b and c give a perimeter=p.*/
if(tmpa + tmpb + tmpc == p && !savedc[tmpc])
{
savedc[tmpc] = 1;
count++;
}
i++;
}
} }
}
i = 2; /* If the current value is greater than the maximum,
tmpa = a; * save the new maximum and the value of p.*/
tmpb = b; if(count > max)
tmpc = c; {
max = count;
res = p;
}
}
/* Check all the triplets obtained multiplying a, b and c clock_gettime(CLOCK_MONOTONIC, &end);
* for integer numbers, until the perimeters exceeds p.*/
while(tmpa + tmpb + tmpc < p)
{
tmpa = a * i;
tmpb = b * i;
tmpc = c * i;
/* Increase counter if the new a, b and c give a perimeter=p.*/ elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
if(tmpa + tmpb + tmpc == p && !savedc[tmpc])
{
savedc[tmpc] = 1;
count++;
}
i++; printf("Project Euler, Problem 39\n");
} printf("Answer: %d\n", res);
}
}
/* If the current value is greater than the maximum, printf("Elapsed time: %.9lf seconds\n", elapsed);
* save the new maximum and the value of p.*/
if(count > max)
{
max = count;
res = p;
}
}
clock_gettime(CLOCK_MONOTONIC, &end); return 0;
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 39\n");
printf("Answer: %d\n", res);
printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0;
} }

136
C/p040.c
View File

@ -8,86 +8,88 @@
* *
* d_1 × d_10 × d_100 × d_1000 × d_10000 × d_100000 × d_1000000*/ * d_1 × d_10 × d_100 × d_1000 × d_10000 × d_100000 × d_1000000*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <time.h> #include <time.h>
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int i, value, n; int i, value, n;
int digits[1000005]; int digits[1000005];
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
i = 1; i = 1;
value = 1; value = 1;
/* Loop on all numbers and put the digits in the right place /* Loop on all numbers and put the digits in the right place
* in an array. Use modulo and division to get the digits * in an array. Use modulo and division to get the digits
* for numbers with more than one digit.*/ * for numbers with more than one digit.*/
while(i <= 1000000) while(i <= 1000000)
{ {
if(value < 10) if(value < 10)
{ {
digits[i-1] = value; digits[i-1] = value;
i++; i++;
} }
else if(value < 100) else if(value < 100)
{ {
digits[i-1] = value / 10; digits[i-1] = value / 10;
digits[i] = value % 10; digits[i] = value % 10;
i += 2; i += 2;
} }
else if(value < 1000) else if(value < 1000)
{ {
digits[i-1] = value / 100; digits[i-1] = value / 100;
digits[i] = (value / 10) % 10; digits[i] = (value / 10) % 10;
digits[i+1] = value % 10; digits[i+1] = value % 10;
i += 3; i += 3;
} }
else if(value < 10000) else if(value < 10000)
{ {
digits[i-1] = value / 1000; digits[i-1] = value / 1000;
digits[i] = (value / 100) % 10; digits[i] = (value / 100) % 10;
digits[i+1] = (value / 10) % 10; digits[i+1] = (value / 10) % 10;
digits[i+2] = value % 10; digits[i+2] = value % 10;
i += 4; i += 4;
} }
else if(value < 100000) else if(value < 100000)
{ {
digits[i-1] = value / 10000; digits[i-1] = value / 10000;
digits[i] = (value / 1000) % 10; digits[i] = (value / 1000) % 10;
digits[i+1] = (value / 100) % 10; digits[i+1] = (value / 100) % 10;
digits[i+2] = (value / 10) % 10; digits[i+2] = (value / 10) % 10;
digits[i+3] = value % 10; digits[i+3] = value % 10;
i += 5; i += 5;
} }
else if(value < 1000000) else if(value < 1000000)
{ {
digits[i-1] = value / 100000; digits[i-1] = value / 100000;
digits[i] = (value / 10000) % 10; digits[i] = (value / 10000) % 10;
digits[i+1] = (value / 1000) % 10; digits[i+1] = (value / 1000) % 10;
digits[i+2] = (value / 100) % 10; digits[i+2] = (value / 100) % 10;
digits[i+3] = (value / 10) % 10; digits[i+3] = (value / 10) % 10;
digits[i+4] = value % 10; digits[i+4] = value % 10;
i += 6; i += 6;
} }
value++; value++;
} }
/* Calculate the product.*/ /* Calculate the product.*/
n = digits[0] * digits[9] * digits[99] * digits[999] * digits[9999] * digits[99999] * digits[999999]; n = digits[0] * digits[9] * digits[99] * digits[999] * digits[9999] * digits[99999] * digits[999999];
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 40\n"); printf("Project Euler, Problem 40\n");
printf("Answer: %d\n", n); printf("Answer: %d\n", n);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0; return 0;
} }

View File

@ -3,6 +3,8 @@
* *
* What is the largest n-digit pandigital prime that exists?*/ * What is the largest n-digit pandigital prime that exists?*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <math.h> #include <math.h>
@ -13,53 +15,53 @@ int count_digits(int n);
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
/* 8- and 9-digit pandigital numbers can't be prime, because /* 8- and 9-digit pandigital numbers can't be prime, because
* 1+2+...+8=36, which is divisible by 3, and 36+9=45 which is * 1+2+...+8=36, which is divisible by 3, and 36+9=45 which is
* also divisible by 3, and therefore the whole number is divisible * also divisible by 3, and therefore the whole number is divisible
* by 3. So we can start from the largest 7-digit pandigital number, * by 3. So we can start from the largest 7-digit pandigital number,
* until we find a prime.*/ * until we find a prime.*/
int i = 7654321; int i = 7654321;
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
while(i > 0) while(i > 0)
{ {
if(is_pandigital(i, count_digits(i)) && is_prime(i)) if(is_pandigital(i, count_digits(i)) && is_prime(i))
{ {
break; break;
} }
/*Skipping the even numbers.*/ /*Skipping the even numbers.*/
i -= 2; i -= 2;
} }
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 41\n"); printf("Project Euler, Problem 41\n");
printf("Answer: %d\n", i); printf("Answer: %d\n", i);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0; return 0;
} }
int count_digits(int n) int count_digits(int n)
{ {
int i = 0; int i = 0;
if(n == 0) if(n == 0)
{ {
return 1; return 1;
} }
while(n > 0) while(n > 0)
{ {
i++; i++;
n /= 10; n /= 10;
} }
return i; return i;
} }

132
C/p042.c
View File

@ -8,6 +8,8 @@
* Using words.txt (right click and 'Save Link/Target As...'), a 16K text file containing nearly two-thousand common English words, * Using words.txt (right click and 'Save Link/Target As...'), a 16K text file containing nearly two-thousand common English words,
* how many are triangle words?*/ * how many are triangle words?*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
@ -17,93 +19,93 @@ int is_triang(int n);
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int i, j, n, len, value, count = 0; int i, j, n, len, value, count = 0;
char *line, **words; char *line, **words;
double elapsed; double elapsed;
FILE *fp; FILE *fp;
struct timespec start, end; struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
if((fp = fopen("words.txt", "r")) == NULL) if((fp = fopen("words.txt", "r")) == NULL)
{ {
fprintf(stderr, "Error while opening file %s\n", "words.txt"); fprintf(stderr, "Error while opening file %s\n", "words.txt");
return 1; return 1;
} }
fscanf(fp, "%ms", &line); fscanf(fp, "%ms", &line);
fclose(fp); fclose(fp);
n = 1; n = 1;
len = strlen(line); len = strlen(line);
/* Count the words.*/ /* Count the words.*/
for(i = 0; i < len; i++) for(i = 0; i < len; i++)
{ {
if(line[i] == ',') if(line[i] == ',')
{ {
n++; n++;
} }
} }
if((words = (char **)malloc(n*sizeof(char *))) == NULL) if((words = (char **)malloc(n*sizeof(char *))) == NULL)
{ {
fprintf(stderr, "Error while allocating memory\n"); fprintf(stderr, "Error while allocating memory\n");
return 1; return 1;
} }
/* Save the words in an array of strings.*/ /* Save the words in an array of strings.*/
words[0] = strtok(line, ",\""); words[0] = strtok(line, ",\"");
for(i = 1; i < n; i++) for(i = 1; i < n; i++)
{ {
words[i] = strtok(NULL, ",\""); words[i] = strtok(NULL, ",\"");
} }
/* For each word, calculate its value and check if it's a triangle number.*/ /* For each word, calculate its value and check if it's a triangle number.*/
for(i = 0; i < n; i++) for(i = 0; i < n; i++)
{ {
value = 0; value = 0;
len = strlen(words[i]); len = strlen(words[i]);
for(j = 0; j < len; j++) for(j = 0; j < len; j++)
{ {
value += (words[i][j] - 'A' + 1); value += (words[i][j] - 'A' + 1);
} }
if(is_triang(value)) if(is_triang(value))
{ {
count++; count++;
} }
} }
free(line); free(line);
free(words); free(words);
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec-start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec-start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 42\n"); printf("Project Euler, Problem 42\n");
printf("Answer: %d\n", count); printf("Answer: %d\n", count);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0; return 0;
} }
int is_triang(int n) int is_triang(int n)
{ {
int i, j; int i, j;
for(i = 1, j = 1; j <= n; i++, j += i) for(i = 1, j = 1; j <= n; i++, j += i)
{ {
if(n == j) if(n == j)
{ {
return 1; return 1;
} }
} }
return 0; return 0;
} }

156
C/p043.c
View File

@ -13,6 +13,8 @@
* *
* Find the sum of all 0 to 9 pandigital numbers with this property.*/ * Find the sum of all 0 to 9 pandigital numbers with this property.*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <time.h> #include <time.h>
@ -23,116 +25,116 @@ int has_property(int **n);
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int i; int i;
int **n; int **n;
long int sum = 0; long int sum = 0;
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
if((n = (int **)malloc(10*sizeof(int *))) == NULL) if((n = (int **)malloc(10*sizeof(int *))) == NULL)
{ {
fprintf(stderr, "Error while allocating memory\n"); fprintf(stderr, "Error while allocating memory\n");
return 1; return 1;
} }
for(i = 0; i < 10; i++) for(i = 0; i < 10; i++)
{ {
if((n[i] = (int *)malloc(sizeof(int))) == NULL) if((n[i] = (int *)malloc(sizeof(int))) == NULL)
{ {
fprintf(stderr, "Error while allocating memory\n"); fprintf(stderr, "Error while allocating memory\n");
return 1; return 1;
} }
*n[i] = i; *n[i] = i;
} }
/* Find the next permutation and check if it has the required property. /* Find the next permutation and check if it has the required property.
* Repeat until all the permutations have been found.*/ * Repeat until all the permutations have been found.*/
while(next_permutation((void **)n, 10, compare) != -1) while(next_permutation((void **)n, 10, compare) != -1)
{ {
if(has_property(n)) if(has_property(n))
{ {
sum += *n[0] * 1e9 + *n[1] * 1e8 + *n[2] * 1e7 + *n[3] * 1e6 + *n[4] * 1e5 + sum += *n[0] * 1e9 + *n[1] * 1e8 + *n[2] * 1e7 + *n[3] * 1e6 + *n[4] * 1e5 +
*n[5] * 1e4 + *n[6] * 1e3 + *n[7] * 1e2 + *n[8] * 1e1 + *n[9]; *n[5] * 1e4 + *n[6] * 1e3 + *n[7] * 1e2 + *n[8] * 1e1 + *n[9];
} }
} }
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 43\n"); printf("Project Euler, Problem 43\n");
printf("Answer: %ld\n", sum); printf("Answer: %ld\n", sum);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0; return 0;
} }
int compare(void *a, void *b) int compare(void *a, void *b)
{ {
int *n1, *n2; int *n1, *n2;
n1 = (int *)a; n1 = (int *)a;
n2 = (int *)b; n2 = (int *)b;
return *n1 - *n2; return *n1 - *n2;
} }
/* Function to check if the value has the desired property.*/ /* Function to check if the value has the desired property.*/
int has_property(int **n) int has_property(int **n)
{ {
long int value; long int value;
value = *n[1] * 100 + *n[2] * 10 + *n[3]; value = *n[1] * 100 + *n[2] * 10 + *n[3];
if(value % 2 != 0) if(value % 2 != 0)
{ {
return 0; return 0;
} }
value = *n[2] * 100 + *n[3] * 10 + *n[4]; value = *n[2] * 100 + *n[3] * 10 + *n[4];
if(value % 3 != 0) if(value % 3 != 0)
{ {
return 0; return 0;
} }
value = *n[3] * 100 + *n[4] * 10 + *n[5]; value = *n[3] * 100 + *n[4] * 10 + *n[5];
if(value % 5 != 0) if(value % 5 != 0)
{ {
return 0; return 0;
} }
value = *n[4] * 100 + *n[5] * 10 + *n[6]; value = *n[4] * 100 + *n[5] * 10 + *n[6];
if(value % 7 != 0) if(value % 7 != 0)
{ {
return 0; return 0;
} }
value = *n[5] * 100 + *n[6] * 10 + *n[7]; value = *n[5] * 100 + *n[6] * 10 + *n[7];
if(value % 11 != 0) if(value % 11 != 0)
{ {
return 0; return 0;
} }
value = *n[6] * 100 + *n[7] * 10 + *n[8]; value = *n[6] * 100 + *n[7] * 10 + *n[8];
if(value %13 != 0) if(value %13 != 0)
{ {
return 0; return 0;
} }
value = *n[7] * 100 + *n[8] * 10 + *n[9]; value = *n[7] * 100 + *n[8] * 10 + *n[9];
if(value % 17 != 0) if(value % 17 != 0)
{ {
return 0; return 0;
} }
return 1; return 1;
} }

View File

@ -7,6 +7,8 @@
* Find the pair of pentagonal numbers, Pj and Pk, for which their sum and difference are pentagonal and D = |Pk Pj| is minimised; * Find the pair of pentagonal numbers, Pj and Pk, for which their sum and difference are pentagonal and D = |Pk Pj| is minimised;
* what is the value of D?*/ * what is the value of D?*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <math.h> #include <math.h>
@ -15,42 +17,42 @@
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int n, m, pn, pm, found = 0; int n, m, pn, pm, found = 0;
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
n = 2; n = 2;
/* Check all couples of pentagonal numbers until the right one /* Check all couples of pentagonal numbers until the right one
* is found. Use the function implemented in projecteuler.c to * is found. Use the function implemented in projecteuler.c to
* check if the sum and difference ot the two numbers is pentagonal.*/ * check if the sum and difference ot the two numbers is pentagonal.*/
while(!found) while(!found)
{ {
pn = n * (3 * n - 1) / 2; pn = n * (3 * n - 1) / 2;
for(m = 1; m < n; m++) for(m = 1; m < n; m++)
{ {
pm = m * (3 * m - 1) / 2; pm = m * (3 * m - 1) / 2;
if(is_pentagonal(pn+pm) && is_pentagonal(pn-pm)) if(is_pentagonal(pn+pm) && is_pentagonal(pn-pm))
{ {
found = 1; found = 1;
break; break;
} }
} }
n++; n++;
} }
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 44\n"); printf("Project Euler, Problem 44\n");
printf("Answer: %d\n", pn-pm); printf("Answer: %d\n", pn-pm);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0; return 0;
} }

View File

@ -8,6 +8,8 @@
* *
* Find the next triangle number that is also pentagonal and hexagonal.*/ * Find the next triangle number that is also pentagonal and hexagonal.*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <math.h> #include <math.h>
@ -16,37 +18,37 @@
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int found = 0; int found = 0;
long int i, n; long int i, n;
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
i = 143; i = 143;
while(!found) while(!found)
{ {
i++; i++;
/* Hexagonal numbers are also triangle numbers, so it's sufficient /* Hexagonal numbers are also triangle numbers, so it's sufficient
* to generate hexagonal numbers (starting from H_144) and check if * to generate hexagonal numbers (starting from H_144) and check if
* they're also pentagonal.*/ * they're also pentagonal.*/
n = i * (2 * i - 1); n = i * (2 * i - 1);
if(is_pentagonal(n)) if(is_pentagonal(n))
{ {
found = 1; found = 1;
} }
} }
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 45\n"); printf("Project Euler, Problem 45\n");
printf("Answer: %ld\n", n); printf("Answer: %ld\n", n);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0; return 0;
} }

104
C/p046.c
View File

@ -11,6 +11,8 @@
* *
* What is the smallest odd composite that cannot be written as the sum of a prime and twice a square?*/ * What is the smallest odd composite that cannot be written as the sum of a prime and twice a square?*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <math.h> #include <math.h>
@ -25,73 +27,73 @@ int *primes;
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int i, found = 0; int i, found = 0;
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
if((primes = sieve(N)) == NULL) if((primes = sieve(N)) == NULL)
{ {
fprintf(stderr, "Error! Sieve function returned NULL\n"); fprintf(stderr, "Error! Sieve function returned NULL\n");
return 1; return 1;
} }
/* For every odd number, check if it's prime, if it is check /* For every odd number, check if it's prime, if it is check
* if it satisfies the Goldbach property. Continue until the * if it satisfies the Goldbach property. Continue until the
* first number that doesn't is found.*/ * first number that doesn't is found.*/
for(i = 3; !found && i < N; i += 2) for(i = 3; !found && i < N; i += 2)
{ {
if(!primes[i]) if(!primes[i])
{ {
if(!goldbach(i)) if(!goldbach(i))
{ {
found = 1; found = 1;
} }
} }
} }
free(primes); free(primes);
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 46\n"); printf("Project Euler, Problem 46\n");
printf("Answer: %d\n", i-2); printf("Answer: %d\n", i-2);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0; return 0;
} }
int goldbach(int n) int goldbach(int n)
{ {
int i, j, tmp; int i, j, tmp;
/* Check every prime smaller than n.*/ /* Check every prime smaller than n.*/
for(i = 3; i < n; i += 2) for(i = 3; i < n; i += 2)
{ {
if(primes[i]) if(primes[i])
{ {
j = 1; j = 1;
/* Check if summing twice a square to the prime number /* Check if summing twice a square to the prime number
* gives n. Return 1 when succeeding.*/ * gives n. Return 1 when succeeding.*/
do do
{
tmp = i + 2 * j * j;
if(tmp == n)
{ {
return 1; tmp = i + 2 * j * j;
}
j++; if(tmp == n)
}while(tmp < n); {
} return 1;
} }
/* Return 0 if no solution is found.*/ j++;
return 0; } while(tmp < n);
}
}
/* Return 0 if no solution is found.*/
return 0;
} }

104
C/p047.c
View File

@ -11,6 +11,8 @@
* *
* Find the first four consecutive integers to have four distinct prime factors each. What is the first of these numbers?*/ * Find the first four consecutive integers to have four distinct prime factors each. What is the first of these numbers?*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <math.h> #include <math.h>
@ -22,74 +24,74 @@ int *count_factors(int n);
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int i, count, res; int i, count, res;
int *factors; int *factors;
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
if((factors = count_factors(N)) == NULL) if((factors = count_factors(N)) == NULL)
{ {
fprintf(stderr, "Error! Count_factors function returned NULL\n"); fprintf(stderr, "Error! Count_factors function returned NULL\n");
return 1; return 1;
} }
count = 0; count = 0;
for(i = 0; i < N; i++) for(i = 0; i < N; i++)
{ {
if(factors[i] == 4) if(factors[i] == 4)
{ {
count++; count++;
} }
else else
{ {
count = 0; count = 0;
} }
if(count == 4) if(count == 4)
{ {
res = i - 3; res = i - 3;
break; break;
} }
} }
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 47\n"); printf("Project Euler, Problem 47\n");
printf("Answer: %d\n", res); printf("Answer: %d\n", res);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0; return 0;
} }
/* Function using a modified sieve of Eratosthenes to count /* Function using a modified sieve of Eratosthenes to count
* the distinct prime factors of each number.*/ * the distinct prime factors of each number.*/
int *count_factors(int n) int *count_factors(int n)
{ {
int i = 2, j; int i = 2, j;
int *factors; int *factors;
if((factors = (int *)calloc(n, sizeof(int))) == NULL) if((factors = (int *)calloc(n, sizeof(int))) == NULL)
{ {
return NULL; return NULL;
} }
while(i < n / 2) while(i < n / 2)
{ {
if(factors[i] == 0) if(factors[i] == 0)
{ {
for(j = i; j < n; j += i) for(j = i; j < n; j += i)
{ {
factors[j]++; factors[j]++;
} }
} }
i++; i++;
} }
return factors; return factors;
} }

View File

@ -8,38 +8,40 @@
#include <time.h> #include <time.h>
#include <gmp.h> #include <gmp.h>
#define _POSIX_C_SOURCE 199309L
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int i; int i;
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
mpz_t power, sum; mpz_t power, sum;
char *res; char *res;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
mpz_init_set_ui(sum, 0); mpz_init_set_ui(sum, 0);
mpz_init(power); mpz_init(power);
/* Simply calculate the sum of the powers using the GMP Library.*/ /* Simply calculate the sum of the powers using the GMP Library.*/
for(i = 1; i <= 1000; i++) for(i = 1; i <= 1000; i++)
{ {
mpz_ui_pow_ui(power, i, i); mpz_ui_pow_ui(power, i, i);
mpz_add(sum, sum, power); mpz_add(sum, sum, power);
} }
res = mpz_get_str(NULL, 10, sum); res = mpz_get_str(NULL, 10, sum);
mpz_clears(power, sum, NULL); mpz_clears(power, sum, NULL);
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 48\n"); printf("Project Euler, Problem 48\n");
printf("Answer: %s\n", res+strlen(res)-10); printf("Answer: %s\n", res+strlen(res)-10);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0; return 0;
} }

128
C/p049.c
View File

@ -6,6 +6,8 @@
* *
* What 12-digit number do you form by concatenating the three terms in this sequence?*/ * What 12-digit number do you form by concatenating the three terms in this sequence?*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <math.h> #include <math.h>
@ -20,86 +22,86 @@ int *primes;
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int i = 1489, j, found = 0; int i = 1489, j, found = 0;
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
if((primes = sieve(N)) == NULL) if((primes = sieve(N)) == NULL)
{ {
fprintf(stderr, "Error! Sieve function returned NULL\n"); fprintf(stderr, "Error! Sieve function returned NULL\n");
return 1; return 1;
} }
/* Starting from i=1489 (bigger than the first number in the sequence given in the problem), /* Starting from i=1489 (bigger than the first number in the sequence given in the problem),
* check odd numbers. If they're prime, loop on even numbers j (odd+even=odd, odd+odd=even and * check odd numbers. If they're prime, loop on even numbers j (odd+even=odd, odd+odd=even and
* we need odd numbers because we're looking for primes) up to 4254 (1489+2*4256=10001 which has * we need odd numbers because we're looking for primes) up to 4254 (1489+2*4256=10001 which has
* 5 digits.*/ * 5 digits.*/
while(i < N) while(i < N)
{ {
if(primes[i]) if(primes[i])
{ {
for(j = 2; j < 4255; j += 2) for(j = 2; j < 4255; j += 2)
{
/* If i, i+j and i+2*j are all primes and they have
* all the same digits, the result has been found.*/
if(i + 2 * j < N && primes[i+j] && primes[i+2*j] &&
is_permutation(i, i+j) && is_permutation(i, i+2*j))
{ {
found = 1; /* If i, i+j and i+2*j are all primes and they have
break; * all the same digits, the result has been found.*/
if(i + 2 * j < N && primes[i+j] && primes[i+2*j] &&
is_permutation(i, i+j) && is_permutation(i, i+2*j))
{
found = 1;
break;
}
} }
} }
} if(found)
if(found) {
{ break;
break; }
} i += 2;
i += 2; }
}
free(primes); free(primes);
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 49\n"); printf("Project Euler, Problem 49\n");
printf("Answer: %d%d%d\n", i, i+j, i+2*j); printf("Answer: %d%d%d\n", i, i+j, i+2*j);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0; return 0;
} }
int is_permutation(int a, int b) int is_permutation(int a, int b)
{ {
int i; int i;
int digits1[10] = {0}, digits2[10] = {0}; int digits1[10] = {0}, digits2[10] = {0};
/* Get digits of a.*/ /* Get digits of a.*/
while(a > 0) while(a > 0)
{ {
digits1[a%10]++; digits1[a%10]++;
a /= 10; a /= 10;
} }
/* Get digits of b.*/ /* Get digits of b.*/
while(b > 0) while(b > 0)
{ {
digits2[b%10]++; digits2[b%10]++;
b /= 10; b /= 10;
} }
/* If they're not the same, return 0.*/ /* If they're not the same, return 0.*/
for(i = 0; i < 10; i++) for(i = 0; i < 10; i++)
{ {
if(digits1[i] != digits2[i]) if(digits1[i] != digits2[i])
{ {
return 0; return 0;
} }
} }
return 1; return 1;
} }

124
C/p050.c
View File

@ -8,6 +8,8 @@
* *
* Which prime, below one-million, can be written as the sum of the most consecutive primes?*/ * Which prime, below one-million, can be written as the sum of the most consecutive primes?*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <math.h> #include <math.h>
@ -18,78 +20,78 @@
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int i, j, max = 0, max_p = 0, sum, count; int i, j, max = 0, max_p = 0, sum, count;
int *primes; int *primes;
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
if((primes = sieve(N)) == NULL) if((primes = sieve(N)) == NULL)
{ {
fprintf(stderr, "Error! Sieve function returned NULL\n"); fprintf(stderr, "Error! Sieve function returned NULL\n");
return 1; return 1;
} }
/* Starting from a prime i, add consecutive primes until the /* Starting from a prime i, add consecutive primes until the
* sum exceeds the limit, every time the sum is also a prime * sum exceeds the limit, every time the sum is also a prime
* save the value and the count if the count is larger than the * save the value and the count if the count is larger than the
* current maximum. Repeat for all primes below N. * current maximum. Repeat for all primes below N.
* A separate loop is used for i=2, so later only odd numbers are * A separate loop is used for i=2, so later only odd numbers are
* checked for primality.*/ * checked for primality.*/
i = 2; i = 2;
count = 1; count = 1;
sum = i; sum = i;
for(j = i + 1; j < N && sum < N; j++) for(j = i + 1; j < N && sum < N; j++)
{ {
if(primes[j]) if(primes[j])
{ {
sum += j; sum += j;
count++; count++;
if(sum < N && primes[sum] && count > max) if(sum < N && primes[sum] && count > max)
{
max = count;
max_p = sum;
}
}
}
for(i = 3; i < N; i += 2)
{
if(primes[i])
{
count = 1;
sum = i;
for(j = i + 2; j < N && sum < N; j += 2)
{
if(primes[j])
{ {
sum += j; max = count;
count++; max_p = sum;
if(sum < N && primes[sum] && count > max)
{
max = count;
max_p = sum;
}
} }
} }
} }
}
free(primes); for(i = 3; i < N; i += 2)
{
if(primes[i])
{
count = 1;
sum = i;
clock_gettime(CLOCK_MONOTONIC, &end); for(j = i + 2; j < N && sum < N; j += 2)
{
if(primes[j])
{
sum += j;
count++;
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; if(sum < N && primes[sum] && count > max)
{
max = count;
max_p = sum;
}
}
}
}
}
printf("Project Euler, Problem 50\n"); free(primes);
printf("Answer: %d\n", max_p);
printf("Elapsed time: %.9lf seconds\n", elapsed); clock_gettime(CLOCK_MONOTONIC, &end);
return 0; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 50\n");
printf("Answer: %d\n", max_p);
printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0;
} }

178
C/p051.c
View File

@ -7,6 +7,8 @@
* Find the smallest prime which, by replacing part of the number (not necessarily adjacent digits) with the same digit, is part of an eight prime * Find the smallest prime which, by replacing part of the number (not necessarily adjacent digits) with the same digit, is part of an eight prime
* value family.*/ * value family.*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
@ -23,119 +25,119 @@ int *primes;
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int i; int i;
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
/* N set to 1000000 as a reasonable limit, which turns out to be enough.*/ /* N set to 1000000 as a reasonable limit, which turns out to be enough.*/
if((primes = sieve(N)) == NULL) if((primes = sieve(N)) == NULL)
{ {
fprintf(stderr, "Error! Sieve function returned NULL\n"); fprintf(stderr, "Error! Sieve function returned NULL\n");
return 1; return 1;
} }
/* Checking only odd numbers with at least 4 digits.*/ /* Checking only odd numbers with at least 4 digits.*/
for(i = 1001; i < N; i += 2) for(i = 1001; i < N; i += 2)
{ {
/* The family of numbers needs to have at least one of 0, 1 or 2 as /* The family of numbers needs to have at least one of 0, 1 or 2 as
* repeated digits, otherwise we can't get a 8 number family (there * repeated digits, otherwise we can't get a 8 number family (there
* are only 7 other digits). Also, the number of repeated digits must * are only 7 other digits). Also, the number of repeated digits must
* be 3, otherwise at least 3 resulting numbers will be divisible by 3. * be 3, otherwise at least 3 resulting numbers will be divisible by 3.
* So the smallest number of this family must have three 0s, three 1s or * So the smallest number of this family must have three 0s, three 1s or
* three 2s.*/ * three 2s.*/
if(count_digit(i, 0) >= 3 || count_digit(i, 1) >= 3 || if(count_digit(i, 0) >= 3 || count_digit(i, 1) >= 3 ||
count_digit(i, 2) >= 3) count_digit(i, 2) >= 3)
{ {
/* If i is prime, try replacing digits, if obtaining 8 primes, then /* If i is prime, try replacing digits, if obtaining 8 primes, then
* this is the result.*/ * this is the result.*/
if(primes[i] && replace(i) == 8) if(primes[i] && replace(i) == 8)
{ {
break; break;
} }
} }
} }
free(primes); free(primes);
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 51\n"); printf("Project Euler, Problem 51\n");
printf("Answer: %d\n", i); printf("Answer: %d\n", i);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0; return 0;
} }
int count_digit(int n, int d) int count_digit(int n, int d)
{ {
int count = 0; int count = 0;
while(n > 0) while(n > 0)
{ {
if(n % 10 == d) if(n % 10 == d)
{ {
count++; count++;
} }
n /= 10; n /= 10;
} }
return count; return count;
} }
int replace(int n) int replace(int n)
{ {
int i, j, k, w, l, count, max = 0, s_to_n; int i, j, k, w, l, count, max = 0, s_to_n;
char n_to_s[7]; char n_to_s[7];
sprintf(n_to_s, "%d", n); sprintf(n_to_s, "%d", n);
l = strlen(n_to_s); l = strlen(n_to_s);
for(i = 0; i < l - 3; i++) for(i = 0; i < l - 3; i++)
{ {
for(j = i + 1; j < l - 2; j++) for(j = i + 1; j < l - 2; j++)
{ {
/* Replacing the last digit can't give 8 primes, because at least /* Replacing the last digit can't give 8 primes, because at least
* six of the numbers obtained will be divisible by 2 and/or 5.*/ * six of the numbers obtained will be divisible by 2 and/or 5.*/
for(k = j + 1; k < l - 1; k++) for(k = j + 1; k < l - 1; k++)
{
count = 0;
for(w = 0; w < 10; w++)
{ {
if(i == 0 && w == 0) count = 0;
{
continue;
}
sprintf(n_to_s, "%d", n); for(w = 0; w < 10; w++)
n_to_s[i] = w + '0'; {
n_to_s[j] = w + '0'; if(i == 0 && w == 0)
n_to_s[k] = w + '0'; {
s_to_n = atoi(n_to_s); continue;
}
if(primes[s_to_n]) sprintf(n_to_s, "%d", n);
{ n_to_s[i] = w + '0';
if(count == 0 && s_to_n != n) n_to_s[j] = w + '0';
{ n_to_s[k] = w + '0';
continue; s_to_n = atoi(n_to_s);
}
count++; if(primes[s_to_n])
} {
if(count == 0 && s_to_n != n)
{
continue;
}
count++;
}
}
if(count > max)
{
max = count;
}
} }
}
}
if(count > max) return max;
{
max = count;
}
}
}
}
return max;
} }

View File

@ -2,6 +2,8 @@
* *
* Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same digits.*/ * Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same digits.*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <time.h> #include <time.h>
@ -10,65 +12,65 @@ int is_permutation(int a, int b);
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int i; int i;
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
i = 1; i = 1;
/* Brute force approach, try every integer number until the desired one is found.*/ /* Brute force approach, try every integer number until the desired one is found.*/
while(1) while(1)
{ {
if(is_permutation(i, 2*i) && is_permutation(i, 3*i) && is_permutation(i, 4*i) && if(is_permutation(i, 2*i) && is_permutation(i, 3*i) && is_permutation(i, 4*i) &&
is_permutation(i, 5*i) && is_permutation(i, 6*i)) is_permutation(i, 5*i) && is_permutation(i, 6*i))
{ {
break; break;
} }
i++; i++;
} }
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 52\n"); printf("Project Euler, Problem 52\n");
printf("Answer: %d\n", i); printf("Answer: %d\n", i);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0; return 0;
} }
int is_permutation(int a, int b) int is_permutation(int a, int b)
{ {
int i; int i;
int digits1[10] = {0}, digits2[10] = {0}; int digits1[10] = {0}, digits2[10] = {0};
/* Get digits of a.*/ /* Get digits of a.*/
while(a > 0) while(a > 0)
{ {
digits1[a%10]++; digits1[a%10]++;
a /= 10; a /= 10;
} }
/* Get digits of b.*/ /* Get digits of b.*/
while(b > 0) while(b > 0)
{ {
digits2[b%10]++; digits2[b%10]++;
b /= 10; b /= 10;
} }
/* If they're not the same, return 0.*/ /* If they're not the same, return 0.*/
for(i = 0; i < 10; i++) for(i = 0; i < 10; i++)
{ {
if(digits1[i] != digits2[i]) if(digits1[i] != digits2[i])
{ {
return 0; return 0;
} }
} }
return 1; return 1;
} }

View File

@ -10,6 +10,8 @@
* *
* How many, not necessarily distinct, values of (n r) for 1n100, are greater than one-million?*/ * How many, not necessarily distinct, values of (n r) for 1n100, are greater than one-million?*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <time.h> #include <time.h>
@ -22,63 +24,63 @@ void binomial(mpz_t bin, unsigned long int n, unsigned long int k, mpz_t *factor
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int i, j, count = 0; int i, j, count = 0;
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
mpz_t bin; mpz_t bin;
mpz_t factorials[N+1]; mpz_t factorials[N+1];
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
mpz_init(bin); mpz_init(bin);
mpz_init_set_ui(factorials[0], 1); mpz_init_set_ui(factorials[0], 1);
/* Straightforward brute force approach, using the GMP Library. First /* Straightforward brute force approach, using the GMP Library. First
* calculate all factorials, then use them for the binomial coefficients.*/ * calculate all factorials, then use them for the binomial coefficients.*/
for(i = 1; i <= N; i++) for(i = 1; i <= N; i++)
{ {
mpz_init(factorials[i]); mpz_init(factorials[i]);
mpz_fac_ui(factorials[i], i); mpz_fac_ui(factorials[i], i);
} }
for(i = 23; i <= N; i++) for(i = 23; i <= N; i++)
{ {
for(j = 1; j <= i; j++) for(j = 1; j <= i; j++)
{ {
binomial(bin, i, j, factorials); binomial(bin, i, j, factorials);
if(mpz_cmp_ui(bin, LIMIT) > 0) if(mpz_cmp_ui(bin, LIMIT) > 0)
count++; count++;
} }
} }
mpz_clear(bin); mpz_clear(bin);
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 53\n"); printf("Project Euler, Problem 53\n");
printf("Answer: %d\n", count); printf("Answer: %d\n", count);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0; return 0;
} }
void binomial(mpz_t bin, unsigned long n, unsigned long int k, mpz_t *factorials) void binomial(mpz_t bin, unsigned long n, unsigned long int k, mpz_t *factorials)
{ {
mpz_t num, d1, d2; mpz_t num, d1, d2;
mpz_inits(num, d1, d2, NULL); mpz_inits(num, d1, d2, NULL);
mpz_set(num, factorials[n]); mpz_set(num, factorials[n]);
mpz_set(d1, factorials[k]); mpz_set(d1, factorials[k]);
mpz_set(d2, factorials[n-k]); mpz_set(d2, factorials[n-k]);
mpz_mul(d1, d1, d2); mpz_mul(d1, d1, d2);
mpz_tdiv_q(bin, num, d1); mpz_tdiv_q(bin, num, d1);
mpz_clears(num, d1, d2, NULL); mpz_clears(num, d1, d2, NULL);
} }

1116
C/p054.c

File diff suppressed because it is too large Load Diff

View File

@ -21,6 +21,8 @@
* *
* NOTE: Wording was modified slightly on 24 April 2007 to emphasise the theoretical nature of Lychrel numbers.*/ * NOTE: Wording was modified slightly on 24 April 2007 to emphasise the theoretical nature of Lychrel numbers.*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <time.h> #include <time.h>
@ -31,73 +33,73 @@ int is_lychrel(mpz_t n);
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int i, count = 0; int i, count = 0;
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
mpz_t n; mpz_t n;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
mpz_init(n); mpz_init(n);
/* For each number, use the is_lychrel function to check if the number /* For each number, use the is_lychrel function to check if the number
* is a Lychrel number.*/ * is a Lychrel number.*/
for(i = 1; i < 10000; i++) for(i = 1; i < 10000; i++)
{ {
mpz_set_ui(n, i); mpz_set_ui(n, i);
if(is_lychrel(n)) if(is_lychrel(n))
count++; count++;
} }
mpz_clear(n); mpz_clear(n);
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 55\n"); printf("Project Euler, Problem 55\n");
printf("Answer: %d\n", count); printf("Answer: %d\n", count);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0; return 0;
} }
int is_lychrel(mpz_t n) int is_lychrel(mpz_t n)
{ {
int i; int i;
mpz_t tmp, reverse, rem; mpz_t tmp, reverse, rem;
mpz_inits(tmp, reverse, rem, NULL); mpz_inits(tmp, reverse, rem, NULL);
mpz_set(tmp, n); mpz_set(tmp, n);
/* Run for 50 iterations.*/ /* Run for 50 iterations.*/
for(i = 0; i < 50; i++) for(i = 0; i < 50; i++)
{ {
mpz_set_ui(reverse, 0); mpz_set_ui(reverse, 0);
/* Find the reverse of the given number.*/ /* Find the reverse of the given number.*/
while(mpz_cmp_ui(tmp, 0) > 0) while(mpz_cmp_ui(tmp, 0) > 0)
{ {
mpz_mul_ui(reverse, reverse, 10); mpz_mul_ui(reverse, reverse, 10);
mpz_tdiv_qr_ui(tmp, rem, tmp, 10); mpz_tdiv_qr_ui(tmp, rem, tmp, 10);
mpz_add(reverse, reverse, rem); mpz_add(reverse, reverse, rem);
} }
/* Add the reverse to the original number.*/ /* Add the reverse to the original number.*/
mpz_add(tmp, n, reverse); mpz_add(tmp, n, reverse);
/* If the sum is a palindrome, the number is not a Lychrel number.*/ /* If the sum is a palindrome, the number is not a Lychrel number.*/
if(is_palindrome_mpz(tmp, 10)) if(is_palindrome_mpz(tmp, 10))
{ {
mpz_clears(tmp, reverse, rem, NULL); mpz_clears(tmp, reverse, rem, NULL);
return 0; return 0;
} }
mpz_set(n, tmp); mpz_set(n, tmp);
} }
mpz_clears(tmp, reverse, rem, NULL); mpz_clears(tmp, reverse, rem, NULL);
return 1; return 1;
} }

View File

@ -3,6 +3,8 @@
* *
* Considering natural numbers of the form, a^b, where a, b < 100, what is the maximum digital sum?*/ * Considering natural numbers of the form, a^b, where a, b < 100, what is the maximum digital sum?*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <time.h> #include <time.h>
@ -10,41 +12,41 @@
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int a, b, sum, max = 0; int a, b, sum, max = 0;
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
mpz_t pow; mpz_t pow;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
mpz_init(pow); mpz_init(pow);
/* Straightforward brute force approach using the GMP Library.*/ /* Straightforward brute force approach using the GMP Library.*/
for(a = 1; a < 100; a++) for(a = 1; a < 100; a++)
{ {
for(b = 1; b < 100; b++) for(b = 1; b < 100; b++)
{ {
mpz_ui_pow_ui(pow, a, b); mpz_ui_pow_ui(pow, a, b);
sum = 0; sum = 0;
while(mpz_cmp_ui(pow, 0)) while(mpz_cmp_ui(pow, 0))
sum += mpz_tdiv_q_ui(pow, pow, 10); sum += mpz_tdiv_q_ui(pow, pow, 10);
if(sum > max) if(sum > max)
max = sum; max = sum;
} }
} }
mpz_clear(pow); mpz_clear(pow);
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 56\n"); printf("Project Euler, Problem 56\n");
printf("Answer: %d\n", max); printf("Answer: %d\n", max);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0; return 0;
} }

View File

@ -14,6 +14,8 @@
* *
* In the first one-thousand expansions, how many fractions contain a numerator with more digits than the denominator?*/ * In the first one-thousand expansions, how many fractions contain a numerator with more digits than the denominator?*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <time.h> #include <time.h>
@ -23,64 +25,64 @@ int count_digits(mpz_t n);
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int i, count = 0; int i, count = 0;
mpz_t n, d, d2; mpz_t n, d, d2;
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
mpz_init_set_ui(n, 1); mpz_init_set_ui(n, 1);
mpz_init_set_ui(d, 1); mpz_init_set_ui(d, 1);
mpz_init(d2); mpz_init(d2);
/* If n/d is the current term of the expansion, the next term can be calculated as /* If n/d is the current term of the expansion, the next term can be calculated as
* (n+2d)/(n+d). Using the GMP Library the problem becomes trivial.*/ * (n+2d)/(n+d). Using the GMP Library the problem becomes trivial.*/
for(i = 1; i < 1000; i++) for(i = 1; i < 1000; i++)
{ {
mpz_mul_ui(d2, d, 2); mpz_mul_ui(d2, d, 2);
mpz_add(d, n, d); mpz_add(d, n, d);
mpz_add(n, n, d2); mpz_add(n, n, d2);
if(count_digits(n) > count_digits(d)) if(count_digits(n) > count_digits(d))
{ {
count++; count++;
} }
} }
mpz_clears(n, d, d2, NULL); mpz_clears(n, d, d2, NULL);
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 57\n"); printf("Project Euler, Problem 57\n");
printf("Answer: %d\n", count); printf("Answer: %d\n", count);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0; return 0;
} }
int count_digits(mpz_t n) int count_digits(mpz_t n)
{ {
int count = 0; int count = 0;
mpz_t value; mpz_t value;
if(mpz_cmp_ui(n, 0) == 0) if(mpz_cmp_ui(n, 0) == 0)
{ {
return 1; return 1;
} }
mpz_init_set(value, n); mpz_init_set(value, n);
while(mpz_cmp_ui(value, 0)) while(mpz_cmp_ui(value, 0))
{ {
mpz_tdiv_q_ui(value, value, 10); mpz_tdiv_q_ui(value, value, 10);
count++; count++;
} }
mpz_clear(value); mpz_clear(value);
return count; return count;
} }

View File

@ -14,6 +14,8 @@
* If one complete new layer is wrapped around the spiral above, a square spiral with side length 9 will be formed. If this process is continued, * If one complete new layer is wrapped around the spiral above, a square spiral with side length 9 will be formed. If this process is continued,
* what is the side length of the square spiral for which the ratio of primes along both diagonals first falls below 10%?*/ * what is the side length of the square spiral for which the ratio of primes along both diagonals first falls below 10%?*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <math.h> #include <math.h>
@ -22,57 +24,57 @@
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int i = 1, l = 1, step = 2, count = 0, diag = 5; int i = 1, l = 1, step = 2, count = 0, diag = 5;
double ratio, elapsed; double ratio, elapsed;
struct timespec start, end; struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
/* Starting with 1, the next four numbers in the diagonal are 3 (1+2), 5 (1+2+2), 7 (1+2+2+2) /* Starting with 1, the next four numbers in the diagonal are 3 (1+2), 5 (1+2+2), 7 (1+2+2+2)
* and 9 (1+2+2+2+2). Check which are prime, increment the counter every time a new prime is * and 9 (1+2+2+2+2). Check which are prime, increment the counter every time a new prime is
* found, and divide by the number of elements of the diagonal, which are increase by 4 at * found, and divide by the number of elements of the diagonal, which are increase by 4 at
* every cycle. The next four number added to the diagonal are 13 (9+4), 17 (9+4+4), 21 and 25. * every cycle. The next four number added to the diagonal are 13 (9+4), 17 (9+4+4), 21 and 25.
* Then 25+6 etc., at every cycle the step is increased by 2. Continue until the ratio goes below 0.1.*/ * Then 25+6 etc., at every cycle the step is increased by 2. Continue until the ratio goes below 0.1.*/
do do
{ {
i += step; i += step;
if(is_prime(i)) if(is_prime(i))
{ {
count++; count++;
} }
i += step; i += step;
if(is_prime(i)) if(is_prime(i))
{ {
count++; count++;
} }
i += step; i += step;
if(is_prime(i)) if(is_prime(i))
{ {
count++; count++;
} }
i += step; i += step;
ratio = (double)count / diag; ratio = (double)count / diag;
step += 2; step += 2;
diag += 4; diag += 4;
l += 2; l += 2;
}while(ratio >= 0.1); } while(ratio >= 0.1);
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 58\n"); printf("Project Euler, Problem 58\n");
printf("Answer: %d\n", l); printf("Answer: %d\n", l);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0; return 0;
} }

View File

@ -16,6 +16,8 @@
* encrypted ASCII codes, and the knowledge that the plain text must contain common English words, decrypt the message and find the sum of the * encrypted ASCII codes, and the knowledge that the plain text must contain common English words, decrypt the message and find the sum of the
* ASCII values in the original text.*/ * ASCII values in the original text.*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>

140
C/p060.c
View File

@ -4,6 +4,8 @@
* *
* Find the lowest sum for a set of five primes for which any two primes concatenate to produce another prime.*/ * Find the lowest sum for a set of five primes for which any two primes concatenate to produce another prime.*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <math.h> #include <math.h>
@ -18,97 +20,97 @@ int *primes;
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int found = 0, p1, p2, p3, p4, p5, n; int found = 0, p1, p2, p3, p4, p5, n;
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
if((primes = sieve(N)) == NULL) if((primes = sieve(N)) == NULL)
{ {
fprintf(stderr, "Error! Sieve function returned NULL\n"); fprintf(stderr, "Error! Sieve function returned NULL\n");
return 1; return 1;
} }
/* Straightforward brute force approach.*/ /* Straightforward brute force approach.*/
for(p1 = 3; p1 < N && !found; p1 += 2) for(p1 = 3; p1 < N && !found; p1 += 2)
{ {
/* If p1 is not prime, go to the next number.*/ /* If p1 is not prime, go to the next number.*/
if(!primes[p1]) if(!primes[p1])
{ {
continue;
}
for(p2 = p1 + 2; p2 < N && !found; p2 += 2)
{
/* If p2 is not prime, or at least one of the possible concatenations of
* p1 and p2 is not prime, go to the next number.*/
if(!primes[p2] || !is_prime(cat(p1, p2)) || !is_prime(cat(p2, p1)))
{
continue; continue;
} }
for(p3 = p2 + 2; p3 < N && !found; p3 += 2) for(p2 = p1 + 2; p2 < N && !found; p2 += 2)
{ {
/* If p3 is not prime, or at least one of the possible concatenations of /* If p2 is not prime, or at least one of the possible concatenations of
* p1, p2 and p3 is not prime, go to the next number.*/ * p1 and p2 is not prime, go to the next number.*/
if(!primes[p3] || !is_prime(cat(p1, p3)) || !is_prime(cat(p3, p1)) || if(!primes[p2] || !is_prime(cat(p1, p2)) || !is_prime(cat(p2, p1)))
!is_prime(cat(p2, p3)) || !is_prime(cat(p3, p2)))
{ {
continue; continue;
} }
for(p4 = p3 + 2; p4 < N && !found; p4 += 2) for(p3 = p2 + 2; p3 < N && !found; p3 += 2)
{ {
/* If p4 is not prime, or at least one of the possible concatenations of /* If p3 is not prime, or at least one of the possible concatenations of
* p1, p2, p3 and p4 is not prime, go to the next number.*/ * p1, p2 and p3 is not prime, go to the next number.*/
if(!primes[p4] || !is_prime(cat(p1, p4)) || !is_prime(cat(p4, p1)) || if(!primes[p3] || !is_prime(cat(p1, p3)) || !is_prime(cat(p3, p1)) ||
!is_prime(cat(p2, p4)) || !is_prime(cat(p4, p2)) || !is_prime(cat(p2, p3)) || !is_prime(cat(p3, p2)))
!is_prime(cat(p3, p4)) || !is_prime(cat(p4, p3))) {
{ continue;
continue; }
}
for(p5 = p4 + 2; p5 < N && !found; p5 += 2) for(p4 = p3 + 2; p4 < N && !found; p4 += 2)
{ {
/* If p5 is not prime, or at least one of the possible concatenations of /* If p4 is not prime, or at least one of the possible concatenations of
* p1, p2, p3, p4 and p5 is not prime, go to the next number.*/ * p1, p2, p3 and p4 is not prime, go to the next number.*/
if(!primes[p5] || !is_prime(cat(p1, p5)) || !is_prime(cat(p5, p1)) || if(!primes[p4] || !is_prime(cat(p1, p4)) || !is_prime(cat(p4, p1)) ||
!is_prime(cat(p2, p5)) || !is_prime(cat(p5, p2)) || !is_prime(cat(p2, p4)) || !is_prime(cat(p4, p2)) ||
!is_prime(cat(p3, p5)) || !is_prime(cat(p5, p3)) || !is_prime(cat(p3, p4)) || !is_prime(cat(p4, p3)))
!is_prime(cat(p4, p5)) || !is_prime(cat(p5, p4))) {
{ continue;
continue; }
}
/* If it gets here, the five values have been found.*/ for(p5 = p4 + 2; p5 < N && !found; p5 += 2)
n = p1 + p2 + p3 + p4 + p5; {
found = 1; /* If p5 is not prime, or at least one of the possible concatenations of
} * p1, p2, p3, p4 and p5 is not prime, go to the next number.*/
if(!primes[p5] || !is_prime(cat(p1, p5)) || !is_prime(cat(p5, p1)) ||
!is_prime(cat(p2, p5)) || !is_prime(cat(p5, p2)) ||
!is_prime(cat(p3, p5)) || !is_prime(cat(p5, p3)) ||
!is_prime(cat(p4, p5)) || !is_prime(cat(p5, p4)))
{
continue;
}
/* If it gets here, the five values have been found.*/
n = p1 + p2 + p3 + p4 + p5;
found = 1;
}
}
} }
} }
} }
}
free(primes); free(primes);
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed=(end.tv_sec-start.tv_sec)+(double)(end.tv_nsec-start.tv_nsec)/1000000000; elapsed=(end.tv_sec-start.tv_sec)+(double)(end.tv_nsec-start.tv_nsec)/1000000000;
printf("Project Euler, Problem 60\n"); printf("Project Euler, Problem 60\n");
printf("Answer: %d\n", n); printf("Answer: %d\n", n);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0; return 0;
} }
int cat(int i, int j) int cat(int i, int j)
{ {
char n[10]; char n[10];
sprintf(n, "%d%d", i, j); sprintf(n, "%d%d", i, j);
return atoi(n); return atoi(n);
} }

256
C/p061.c
View File

@ -17,6 +17,8 @@
* Find the sum of the only ordered set of six cyclic 4-digit numbers for which each polygonal type: triangle, square, pentagonal, * Find the sum of the only ordered set of six cyclic 4-digit numbers for which each polygonal type: triangle, square, pentagonal,
* hexagonal, heptagonal, and octagonal, is represented by a different number in the set.*/ * hexagonal, heptagonal, and octagonal, is represented by a different number in the set.*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <time.h> #include <time.h>
@ -28,94 +30,94 @@ int chain[6], flags[6] = {0};
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int i, n, sum = 0; int i, n, sum = 0;
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
i = 1; i = 1;
n = 1; n = 1;
/* Generate all triangle numbers smaller than 10000*/ /* Generate all triangle numbers smaller than 10000*/
do do
{ {
polygonal[0][n] = 1; polygonal[0][n] = 1;
i++; i++;
n = i * (i + 1) / 2; n = i * (i + 1) / 2;
}while(n < 10000); } while(n < 10000);
i = 1; i = 1;
n = 1; n = 1;
/* Generate all square numbers smaller than 10000.*/ /* Generate all square numbers smaller than 10000.*/
do do
{ {
polygonal[1][n] = 1; polygonal[1][n] = 1;
i++; i++;
n = i * i; n = i * i;
}while(n < 10000); } while(n < 10000);
i = 1; i = 1;
n = 1; n = 1;
/* Generate all pentagonal numbers smaller than 10000.*/ /* Generate all pentagonal numbers smaller than 10000.*/
do do
{ {
polygonal[2][n] = 1; polygonal[2][n] = 1;
i++; i++;
n = i * (3 * i - 1) / 2; n = i * (3 * i - 1) / 2;
}while(n < 10000); } while(n < 10000);
i = 1; i = 1;
n = 1; n = 1;
/* Generate all hexagonal numbers smaller than 10000.*/ /* Generate all hexagonal numbers smaller than 10000.*/
do do
{ {
polygonal[3][n] = 1; polygonal[3][n] = 1;
i++; i++;
n = i * (2 * i - 1); n = i * (2 * i - 1);
}while(n < 10000); } while(n < 10000);
i = 1; i = 1;
n = 1; n = 1;
/* Generate all heptagonal numbers smaller than 10000.*/ /* Generate all heptagonal numbers smaller than 10000.*/
do do
{ {
polygonal[4][n] = 1; polygonal[4][n] = 1;
i++; i++;
n = i * (5 * i - 3) / 2; n = i * (5 * i - 3) / 2;
}while(n < 10000); } while(n < 10000);
i = 1; i = 1;
n = 1; n = 1;
/* Generate all octagonal numbers smaller than 10000.*/ /* Generate all octagonal numbers smaller than 10000.*/
do do
{ {
polygonal[5][n] = 1; polygonal[5][n] = 1;
i++; i++;
n = i * (3 * i - 2); n = i * (3 * i - 2);
}while(n < 10000); } while(n < 10000);
/* Find the requested set of numbers.*/ /* Find the requested set of numbers.*/
if(find_set(0, &sum) == 0) if(find_set(0, &sum) == 0)
{ {
printf("Set not found\n"); printf("Set not found\n");
} }
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 61\n"); printf("Project Euler, Problem 61\n");
printf("Answer: %d\n", sum); printf("Answer: %d\n", sum);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0; return 0;
} }
/* Recursive function to find the required set. It finds a polygonal number, /* Recursive function to find the required set. It finds a polygonal number,
@ -124,72 +126,72 @@ int main(int argc, char **argv)
* backtracking and tries the next polygonal number.*/ * backtracking and tries the next polygonal number.*/
int find_set(int step, int *sum) int find_set(int step, int *sum)
{ {
int i, j; int i, j;
/* Use one polygonal number per type, starting from triangular.*/ /* Use one polygonal number per type, starting from triangular.*/
for(i = 0; i < 6; i++) for(i = 0; i < 6; i++)
{ {
/* If the current type has not been used yet, try it.*/ /* If the current type has not been used yet, try it.*/
if(!flags[i]) if(!flags[i])
{ {
/* Set a flag to record that the current polygonal type has been used.*/ /* Set a flag to record that the current polygonal type has been used.*/
flags[i] = 1; flags[i] = 1;
/* Start from 1010 because numbers finishing with 00, 01, ..., 09 can't /* Start from 1010 because numbers finishing with 00, 01, ..., 09 can't
* be part of the chain.*/ * be part of the chain.*/
for(j = 1010; j < 10000; j++) for(j = 1010; j < 10000; j++)
{
/* If the number doesn't finish with 00, 01, ..., 09 and is poligonal,
* try adding it to the chain and add its value to the total sum.*/
if(j % 100 > 9 && polygonal[i][j])
{ {
/* If it's the first number, just add it as first step in the chain.*/ /* If the number doesn't finish with 00, 01, ..., 09 and is poligonal,
if(step == 0) * try adding it to the chain and add its value to the total sum.*/
{ if(j % 100 > 9 && polygonal[i][j])
chain[step] = j; {
*sum += j; /* If it's the first number, just add it as first step in the chain.*/
if(step == 0)
{
chain[step] = j;
*sum += j;
/* Recursively try to add other numbers to the chain. If a solution /* Recursively try to add other numbers to the chain. If a solution
* is found, return 1.*/ * is found, return 1.*/
if(find_set(step+1, sum)) if(find_set(step+1, sum))
{ {
return 1; return 1;
} }
/* If a solution was not found, backtrack, subtracting the value of /* If a solution was not found, backtrack, subtracting the value of
* the number from the total.*/ * the number from the total.*/
*sum -= j; *sum -= j;
} }
/* If this is the last step and the current number can be added to the chain, /* If this is the last step and the current number can be added to the chain,
* add it, update the sum and return 1. A solution has been found.*/ * add it, update the sum and return 1. A solution has been found.*/
else if(step == 5 && j % 100 == chain[0] / 100 && j / 100 == chain[step-1] % 100) else if(step == 5 && j % 100 == chain[0] / 100 && j / 100 == chain[step-1] % 100)
{ {
chain[step] = j; chain[step] = j;
*sum += j; *sum += j;
return 1; return 1;
} }
/* For every other step, add the number to the chain if possible, then recursively /* For every other step, add the number to the chain if possible, then recursively
* try to add other numbers.*/ * try to add other numbers.*/
else if(step < 5 && j / 100 == chain[step-1] % 100) else if(step < 5 && j / 100 == chain[step-1] % 100)
{ {
chain[step] = j; chain[step] = j;
*sum += j; *sum += j;
if(find_set(step+1, sum)) if(find_set(step+1, sum))
{ {
return 1; return 1;
} }
/* If a solution was not found, backtrack.*/ /* If a solution was not found, backtrack.*/
*sum -= j; *sum -= j;
} }
}
} }
}
/* Remove the flag for the current polygonal type.*/ /* Remove the flag for the current polygonal type.*/
flags[i] = 0; flags[i] = 0;
} }
} }
return 0; return 0;
} }

150
C/p062.c
View File

@ -3,6 +3,8 @@
* *
* Find the smallest cube for which exactly five permutations of its digits are cube.*/ * Find the smallest cube for which exactly five permutations of its digits are cube.*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <time.h> #include <time.h>
@ -14,104 +16,104 @@ int count_digits(long int a);
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int count; int count;
long int i, j, cubes[N]; long int i, j, cubes[N];
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
/* Calculate i^3 for all i smaller than 10000.*/ /* Calculate i^3 for all i smaller than 10000.*/
for(i = 0; i < N; i++) for(i = 0; i < N; i++)
{ {
cubes[i] = i * i * i; cubes[i] = i * i * i;
} }
/* For each cube, check if there are four other cubes which are also /* For each cube, check if there are four other cubes which are also
* a permutation of the first cube.*/ * a permutation of the first cube.*/
for(i = 0; i < N - 5; i++) for(i = 0; i < N - 5; i++)
{ {
count = 1; count = 1;
/* Stop when the limit has been reached, when 5 values have been found or /* Stop when the limit has been reached, when 5 values have been found or
* when j^3 has more digits than i^3 (if they don't have the same digits, * when j^3 has more digits than i^3 (if they don't have the same digits,
* they can't be permutations).*/ * they can't be permutations).*/
for(j = i + 1; j < N && count_digits(cubes[j]) == count_digits(cubes[i]); j++) for(j = i + 1; j < N && count_digits(cubes[j]) == count_digits(cubes[i]); j++)
{ {
if(is_permutation(cubes[i], cubes[j])) if(is_permutation(cubes[i], cubes[j]))
{ {
count++; count++;
} }
if(count == 5) if(count == 5)
{ {
break;
}
}
if(count == 5)
{
break; break;
} }
} }
if(count == 5) clock_gettime(CLOCK_MONOTONIC, &end);
{
break;
}
}
clock_gettime(CLOCK_MONOTONIC, &end); elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; printf("Project Euler, Problem 62\n");
printf("Answer: %ld\n", cubes[i]);
printf("Project Euler, Problem 62\n"); printf("Elapsed time: %.9lf seconds\n", elapsed);
printf("Answer: %ld\n", cubes[i]);
printf("Elapsed time: %.9lf seconds\n", elapsed); return 0;
return 0;
} }
int count_digits(long int a) int count_digits(long int a)
{ {
int count = 0; int count = 0;
if(a == 0) if(a == 0)
{ {
return 1; return 1;
} }
while(a > 0) while(a > 0)
{ {
count++; count++;
a /= 10; a /= 10;
} }
return count; return count;
} }
int is_permutation(long int a, long int b) int is_permutation(long int a, long int b)
{ {
int i; int i;
int digits1[10] = {0}, digits2[10] = {0}; int digits1[10] = {0}, digits2[10] = {0};
/* Get digits of a.*/ /* Get digits of a.*/
while(a > 0) while(a > 0)
{ {
digits1[a%10]++; digits1[a%10]++;
a /= 10; a /= 10;
} }
/* Get digits of b.*/ /* Get digits of b.*/
while(b > 0) while(b > 0)
{ {
digits2[b%10]++; digits2[b%10]++;
b /= 10; b /= 10;
} }
/* If they're not the same, return 0.*/ /* If they're not the same, return 0.*/
for(i = 0; i < 10; i++) for(i = 0; i < 10; i++)
{ {
if(digits1[i] != digits2[i]) if(digits1[i] != digits2[i])
{ {
return 0; return 0;
} }
} }
return 1; return 1;
} }

View File

@ -2,6 +2,8 @@
* *
* How many n-digit positive integers exist which are also an nth power?*/ * How many n-digit positive integers exist which are also an nth power?*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <math.h> #include <math.h>
@ -12,70 +14,70 @@ int count_digits(mpz_t n);
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int i, j, count = 0, finished = 0; int i, j, count = 0, finished = 0;
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
mpz_t p; mpz_t p;
mpz_init(p); mpz_init(p);
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
i = 1; i = 1;
while(!finished) while(!finished)
{ {
/* When j=10, j^i will have i+1 digits (e.g if i=3, 10^3=1000).*/ /* When j=10, j^i will have i+1 digits (e.g if i=3, 10^3=1000).*/
for(j = 1; j < 10; j++) for(j = 1; j < 10; j++)
{ {
mpz_ui_pow_ui(p, j, i); mpz_ui_pow_ui(p, j, i);
if(count_digits(p) == i) if(count_digits(p) == i)
{ {
count++; count++;
} }
} }
/* When 9^i has less than i digits, all the numbers have been found.*/ /* When 9^i has less than i digits, all the numbers have been found.*/
if(count_digits(p) < i) if(count_digits(p) < i)
{ {
finished = 1; finished = 1;
} }
i++; i++;
} }
mpz_clear(p); mpz_clear(p);
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 63\n"); printf("Project Euler, Problem 63\n");
printf("Answer: %d\n", count); printf("Answer: %d\n", count);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0; return 0;
} }
int count_digits(mpz_t n) int count_digits(mpz_t n)
{ {
int count = 0; int count = 0;
mpz_t tmp; mpz_t tmp;
if(mpz_cmp_ui(n, 0) == 0) if(mpz_cmp_ui(n, 0) == 0)
{ {
return 1; return 1;
} }
mpz_init_set(tmp, n); mpz_init_set(tmp, n);
while(mpz_cmp_ui(tmp, 0)) while(mpz_cmp_ui(tmp, 0))
{ {
mpz_tdiv_q_ui(tmp, tmp, 10); mpz_tdiv_q_ui(tmp, tmp, 10);
count++; count++;
} }
return count; return count;
} }

View File

@ -40,6 +40,8 @@
* *
* How many continued fractions for N10000 have an odd period?*/ * How many continued fractions for N10000 have an odd period?*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <math.h> #include <math.h>
@ -50,60 +52,60 @@ int is_square(int n);
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int i, count = 0, period; int i, count = 0, period;
int *fraction; int *fraction;
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
for(i = 2; i <= 10000; i++) for(i = 2; i <= 10000; i++)
{ {
/* Perfect squares are obviously not represented as continued fractions. /* Perfect squares are obviously not represented as continued fractions.
* For all other numbers, calculate their period and check if it's odd.*/ * For all other numbers, calculate their period and check if it's odd.*/
if(!is_square(i)) if(!is_square(i))
{ {
if((fraction = build_sqrt_cont_fraction(i, &period, 300)) == NULL) if((fraction = build_sqrt_cont_fraction(i, &period, 300)) == NULL)
{ {
fprintf(stderr, "Error! Build_cont_fraction function returned NULL\n"); fprintf(stderr, "Error! Build_cont_fraction function returned NULL\n");
return 1; return 1;
} }
if(period % 2 != 0) if(period % 2 != 0)
{ {
count++; count++;
} }
} }
} }
free(fraction); free(fraction);
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 64\n"); printf("Project Euler, Problem 64\n");
printf("Answer: %d\n", count); printf("Answer: %d\n", count);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0; return 0;
} }
int is_square(int n) int is_square(int n)
{ {
int m; int m;
double p; double p;
p = sqrt(n); p = sqrt(n);
m = p; m = p;
if(p == m) if(p == m)
{ {
return 1; return 1;
} }
else else
{ {
return 0; return 0;
} }
} }

View File

@ -27,6 +27,8 @@
* *
* Find the sum of digits in the numerator of the 100th convergent of the continued fraction for e.*/ * Find the sum of digits in the numerator of the 100th convergent of the continued fraction for e.*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <time.h> #include <time.h>
@ -34,55 +36,55 @@
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int i, ai[3] = {1, 2, 1}, count = 4, sum = 0; int i, ai[3] = {1, 2, 1}, count = 4, sum = 0;
mpz_t n0, n1, n2; mpz_t n0, n1, n2;
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
mpz_init_set_ui(n0, 3); mpz_init_set_ui(n0, 3);
mpz_init_set_ui(n1, 8); mpz_init_set_ui(n1, 8);
mpz_init_set_ui(n2, 11); mpz_init_set_ui(n2, 11);
/* For a continued fractions [a_0; a_1, a_2, ...], the numerator of the /* For a continued fractions [a_0; a_1, a_2, ...], the numerator of the
* next convergent N_n=a_n*N_(n-1)+N_(n-2). The first three values for e are * next convergent N_n=a_n*N_(n-1)+N_(n-2). The first three values for e are
* 3, 8 and 11, the next ones are easily calculated, considering that a_n * 3, 8 and 11, the next ones are easily calculated, considering that a_n
* follows a simple pattern: * follows a simple pattern:
* a_1=1, a_2=2, a_3=1 * a_1=1, a_2=2, a_3=1
* a_4=1, a_5=4, a_6=1 * a_4=1, a_5=4, a_6=1
* a_7=1, a_8=6, a_9=1 * a_7=1, a_8=6, a_9=1
* and so on.*/ * and so on.*/
while(count < 100) while(count < 100)
{ {
ai[1] += 2; ai[1] += 2;
for(i = 0; i < 3 && count < 100; i++) for(i = 0; i < 3 && count < 100; i++)
{ {
mpz_set(n0, n1); mpz_set(n0, n1);
mpz_set(n1, n2); mpz_set(n1, n2);
mpz_mul_ui(n2, n1, ai[i]); mpz_mul_ui(n2, n1, ai[i]);
mpz_add(n2, n2, n0); mpz_add(n2, n2, n0);
count++; count++;
} }
} }
/* Sum the digits.*/ /* Sum the digits.*/
while(mpz_cmp_ui(n2, 0)) while(mpz_cmp_ui(n2, 0))
{ {
sum += mpz_tdiv_q_ui(n2, n2, 10); sum += mpz_tdiv_q_ui(n2, n2, 10);
} }
mpz_clears(n0, n1, n2, NULL); mpz_clears(n0, n1, n2, NULL);
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 65\n"); printf("Project Euler, Problem 65\n");
printf("Answer: %d\n", sum); printf("Answer: %d\n", sum);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0; return 0;
} }

View File

@ -18,6 +18,8 @@
* *
* Find the value of D 1000 in minimal solutions of x for which the largest value of x is obtained.*/ * Find the value of D 1000 in minimal solutions of x for which the largest value of x is obtained.*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <math.h> #include <math.h>
@ -29,64 +31,63 @@ int is_square(int n);
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int i, max_d = -1; int i, max_d = -1;
mpz_t x, max; mpz_t x, max;
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
// mpz_init(x); // mpz_init(x);
mpz_init_set_ui(max, 0); mpz_init_set_ui(max, 0);
for(i = 2; i <= 1000; i++) for(i = 2; i <= 1000; i++)
{ {
if(!is_square(i)) if(!is_square(i))
{ {
/* Solve the Diophantine equation x^2-D*y^2=1 (Pell equation)*/ /* Solve the Diophantine equation x^2-D*y^2=1 (Pell equation)*/
if(pell_eq(i, x) == -1) if(pell_eq(i, x) == -1)
{ {
fprintf(stderr, "Error! Pell_eq function failed\n"); fprintf(stderr, "Error! Pell_eq function failed\n");
return 1; return 1;
} }
if(mpz_cmp(x, max) > 0) if(mpz_cmp(x, max) > 0)
{ {
mpz_set(max, x); mpz_set(max, x);
max_d = i; max_d = i;
} }
} }
} }
mpz_clears(x, max, NULL); mpz_clears(x, max, NULL);
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 66\n"); printf("Project Euler, Problem 66\n");
printf("Answer: %d\n", max_d); printf("Answer: %d\n", max_d);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0; return 0;
} }
int is_square(int n) int is_square(int n)
{ {
int m; int m;
double p; double p;
p = sqrt(n); p = sqrt(n);
m = p; m = p;
if(p == m) if(p == m)
{ {
return 1; return 1;
} }
else else
{ {
return 0; return 0;
} }
} }

View File

@ -13,6 +13,8 @@
* If you could check one trillion (1012) routes every second it would take over twenty billion years to check them all. * If you could check one trillion (1012) routes every second it would take over twenty billion years to check them all.
* There is an efficient algorithm to solve it. ;o)*/ * There is an efficient algorithm to solve it. ;o)*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <time.h> #include <time.h>
@ -20,63 +22,63 @@
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int i, j, max; int i, j, max;
int **triang; int **triang;
double elapsed; double elapsed;
FILE *fp; FILE *fp;
struct timespec start, end; struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
if((triang = (int **)malloc(100*sizeof(int *))) == NULL) if((triang = (int **)malloc(100*sizeof(int *))) == NULL)
{ {
fprintf(stderr, "Error while allocating memory\n"); fprintf(stderr, "Error while allocating memory\n");
return 1; return 1;
} }
for(i = 1; i <= 100; i++) for(i = 1; i <= 100; i++)
{ {
if((triang[i-1] = (int *)malloc(i*sizeof(int))) == NULL) if((triang[i-1] = (int *)malloc(i*sizeof(int))) == NULL)
{ {
fprintf(stderr, "Error while allocating memory\n"); fprintf(stderr, "Error while allocating memory\n");
return 1; return 1;
} }
} }
if((fp = fopen("triangle.txt", "r")) == NULL) if((fp = fopen("triangle.txt", "r")) == NULL)
{ {
fprintf(stderr, "Error while opening file %s\n", "triangle.txt"); fprintf(stderr, "Error while opening file %s\n", "triangle.txt");
return 1; return 1;
} }
for(i = 1; i <= 100; i++) for(i = 1; i <= 100; i++)
{ {
for(j = 0; j < i; j++) for(j = 0; j < i; j++)
{ {
fscanf(fp, "%d", &triang[i-1][j]); fscanf(fp, "%d", &triang[i-1][j]);
} }
} }
fclose(fp); fclose(fp);
/* Use the function implemented in projecteuler.c to find the maximum path.*/ /* Use the function implemented in projecteuler.c to find the maximum path.*/
max = find_max_path(triang, 100); max = find_max_path(triang, 100);
for(i = 0; i < 100; i++) for(i = 0; i < 100; i++)
{ {
free(triang[i]); free(triang[i]);
} }
free(triang); free(triang);
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 67\n"); printf("Project Euler, Problem 67\n");
printf("Answer: %d\n", max); printf("Answer: %d\n", max);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0; return 0;
} }

226
C/p068.c
View File

@ -43,6 +43,8 @@
* O * O
*/ */
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
@ -56,79 +58,79 @@ int compare(void *a, void *b);
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int i; int i;
int *eval, **ring; int *eval, **ring;
long int n, max = 0; long int n, max = 0;
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
if((ring = (int **)malloc(10*sizeof(int *))) == NULL) if((ring = (int **)malloc(10*sizeof(int *))) == NULL)
{ {
fprintf(stderr, "Error while allocating memory\n"); fprintf(stderr, "Error while allocating memory\n");
return 1; return 1;
} }
for(i = 0; i < 10; i++) for(i = 0; i < 10; i++)
{ {
if((ring[i] = (int *)malloc(sizeof(int))) == NULL) if((ring[i] = (int *)malloc(sizeof(int))) == NULL)
{ {
fprintf(stderr, "Error while allocating memory\n"); fprintf(stderr, "Error while allocating memory\n");
return 1; return 1;
} }
*ring[i] = i + 1; *ring[i] = i + 1;
} }
/* Check if the first permutation of values is a possible solution.*/ /* Check if the first permutation of values is a possible solution.*/
eval = eval_ring(ring, 5); eval = eval_ring(ring, 5);
/* Convert the vector into an integer number.*/ /* Convert the vector into an integer number.*/
n = array_to_long(eval, 15); n = array_to_long(eval, 15);
if(n > max) if(n > max)
{ {
max = n; max = n;
} }
free(eval); free(eval);
/* Generate all possible permutations, for each one check if /* Generate all possible permutations, for each one check if
* it's a possible solution for the ring and save the maximum.*/ * it's a possible solution for the ring and save the maximum.*/
while(next_permutation((void **)ring, 10, compare) != -1) while(next_permutation((void **)ring, 10, compare) != -1)
{ {
eval = eval_ring(ring, 5); eval = eval_ring(ring, 5);
n = array_to_long(eval, 15); n = array_to_long(eval, 15);
if(n > max) if(n > max)
{ {
max = n; max = n;
} }
free(eval); free(eval);
} }
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 68\n"); printf("Project Euler, Problem 68\n");
printf("Answer: %ld\n", max); printf("Answer: %ld\n", max);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0; return 0;
} }
int compare(void *a, void *b) int compare(void *a, void *b)
{ {
int *n1, *n2; int *n1, *n2;
n1 = (int *)a; n1 = (int *)a;
n2 = (int *)b; n2 = (int *)b;
return *n1 - *n2; return *n1 - *n2;
} }
/* Function to evaluate the ring. The ring is represented as a vector of 2*n elements, /* Function to evaluate the ring. The ring is represented as a vector of 2*n elements,
@ -136,82 +138,82 @@ int compare(void *a, void *b)
* represent the internal ring.*/ * represent the internal ring.*/
int *eval_ring(int **ring, int n) int *eval_ring(int **ring, int n)
{ {
int i, j, magic_val, val; int i, j, magic_val, val;
int *res; int *res;
for(i = 1; i < n; i++) for(i = 1; i < n; i++)
{ {
/* We need to start from the lowest external node, so if /* We need to start from the lowest external node, so if
* the first element in the vector is not the lowest of * the first element in the vector is not the lowest of
* the first n elements (the external elements), the configuration * the first n elements (the external elements), the configuration
* is not a valid one.*/ * is not a valid one.*/
if(*ring[i] < *ring[0]) if(*ring[i] < *ring[0])
{ {
return NULL; return NULL;
} }
} }
if((res = (int *)malloc(3*n*sizeof(int))) == NULL) if((res = (int *)malloc(3*n*sizeof(int))) == NULL)
{ {
fprintf(stderr, "Error while allocating memory\n"); fprintf(stderr, "Error while allocating memory\n");
return NULL; return NULL;
} }
/* Each group of three must have the same value.*/ /* Each group of three must have the same value.*/
magic_val = *ring[0] + *ring[n] + *ring[n+1]; magic_val = *ring[0] + *ring[n] + *ring[n+1];
for(i = 0, j = 0; i < n; i++, j += 3) for(i = 0, j = 0; i < n; i++, j += 3)
{ {
/* We need to find the maximum 16-digit string, this is /* We need to find the maximum 16-digit string, this is
* possible only if the element "10" is used only once, * possible only if the element "10" is used only once,
* i.e. if it's one of the external nodes.*/ * i.e. if it's one of the external nodes.*/
if(*ring[n+i] == 10 || *ring[n+(i+1)%n] == 10) if(*ring[n+i] == 10 || *ring[n+(i+1)%n] == 10)
{ {
return NULL; return NULL;
} }
/* Check that the value of the current three-element group /* Check that the value of the current three-element group
* is the "magic" value.*/ * is the "magic" value.*/
val = *ring[i] + *ring[n+i] + *ring[n+(i+1)%n]; val = *ring[i] + *ring[n+i] + *ring[n+(i+1)%n];
if(val != magic_val) if(val != magic_val)
{ {
return NULL; return NULL;
} }
/* Save the current element group in the result string.*/ /* Save the current element group in the result string.*/
res[j] = *ring[i]; res[j] = *ring[i];
res[j+1] = *ring[n+i]; res[j+1] = *ring[n+i];
res[j+2] = *ring[n+(i+1)%n]; res[j+2] = *ring[n+(i+1)%n];
} }
return res; return res;
} }
/* Function to convert the vector into a long int.*/ /* Function to convert the vector into a long int.*/
long int array_to_long(int *n, int len) long int array_to_long(int *n, int len)
{ {
int i, k = 0; int i, k = 0;
long int res = 0; long int res = 0;
if(n == NULL) if(n == NULL)
{ {
return 0; return 0;
} }
for(i = len - 1; i >= 0; i--) for(i = len - 1; i >= 0; i--)
{ {
res += n[i] * pow(10, k); res += n[i] * pow(10, k);
if(n[i] >= 10) if(n[i] >= 10)
{ {
k += 2; k += 2;
} }
else else
{ {
k++; k++;
} }
} }
return res; return res;
} }

View File

@ -16,6 +16,8 @@
* *
* Find the value of n 1,000,000 for which n/φ(n) is a maximum.*/ * Find the value of n 1,000,000 for which n/φ(n) is a maximum.*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <math.h> #include <math.h>
@ -27,7 +29,7 @@
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int i, res = 1; int i, res = 1;
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
@ -58,9 +60,9 @@ int main(int argc, char **argv)
elapsed = (end.tv_sec-start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec-start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 69\n"); printf("Project Euler, Problem 69\n");
printf("Answer: %d\n", res); printf("Answer: %d\n", res);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0; return 0;
} }

116
C/p070.c
View File

@ -7,6 +7,8 @@
* *
* Find the value of n, 1 < n < 10^7, for which φ(n) is a permutation of n and the ratio n/φ(n) produces a minimum.*/ * Find the value of n, 1 < n < 10^7, for which φ(n) is a permutation of n and the ratio n/φ(n) produces a minimum.*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <math.h> #include <math.h>
@ -20,78 +22,78 @@ int is_permutation(int a, int b);
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int i, a, b, p, n = -1; int i, a, b, p, n = -1;
int *primes; int *primes;
double elapsed, min = DBL_MAX; double elapsed, min = DBL_MAX;
struct timespec start, end; struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
if((primes = sieve(N)) == NULL) if((primes = sieve(N)) == NULL)
{ {
fprintf(stderr, "Error! Sieve function returned NULL\n"); fprintf(stderr, "Error! Sieve function returned NULL\n");
return 1; return 1;
} }
for(i = 2; i < N; i++) for(i = 2; i < N; i++)
{ {
/* When n is prime, phi(n)=(n-1), so to minimize n/phi(n) we should /* When n is prime, phi(n)=(n-1), so to minimize n/phi(n) we should
* use n prime. But n-1 can't be a permutation of n. The second best * use n prime. But n-1 can't be a permutation of n. The second best
* bet is to use semiprimes. For a semiprime n=p*q, phi(n)=(p-1)(q-1). * bet is to use semiprimes. For a semiprime n=p*q, phi(n)=(p-1)(q-1).
* So we check if a number is semiprime, if yes calculate phi, finally * So we check if a number is semiprime, if yes calculate phi, finally
* check if phi(n) is a permutation of n and update the minimum if it's * check if phi(n) is a permutation of n and update the minimum if it's
* smaller.*/ * smaller.*/
if(is_semiprime(i, &a, &b, primes)) if(is_semiprime(i, &a, &b, primes))
{ {
p = phi_semiprime(i, a, b); p = phi_semiprime(i, a, b);
if(is_permutation(p, i) && (double)i / p < min) if(is_permutation(p, i) && (double)i / p < min)
{ {
n = i; n = i;
min = (double)i / p; min = (double)i / p;
} }
} }
} }
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 70\n"); printf("Project Euler, Problem 70\n");
printf("Answer: %d\n", n); printf("Answer: %d\n", n);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0; return 0;
} }
int is_permutation(int a, int b) int is_permutation(int a, int b)
{ {
int i; int i;
int digits1[10] = {0}, digits2[10] = {0}; int digits1[10] = {0}, digits2[10] = {0};
/* Get digits of a.*/ /* Get digits of a.*/
while(a > 0) while(a > 0)
{ {
digits1[a%10]++; digits1[a%10]++;
a /= 10; a /= 10;
} }
/* Get digits of b.*/ /* Get digits of b.*/
while(b > 0) while(b > 0)
{ {
digits2[b%10]++; digits2[b%10]++;
b /= 10; b /= 10;
} }
/* If they're not the same, return 0.*/ /* If they're not the same, return 0.*/
for(i = 0; i < 10; i++) for(i = 0; i < 10; i++)
{ {
if(digits1[i] != digits2[i]) if(digits1[i] != digits2[i])
{ {
return 0; return 0;
} }
} }
return 1; return 1;
} }

View File

@ -9,6 +9,8 @@
* By listing the set of reduced proper fractions for d 1,000,000 in ascending order of size, find the numerator * By listing the set of reduced proper fractions for d 1,000,000 in ascending order of size, find the numerator
* of the fraction immediately to the left of 3/7.*/ * of the fraction immediately to the left of 3/7.*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <time.h> #include <time.h>
@ -18,47 +20,47 @@
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int i, j, n, d, max_n; int i, j, n, d, max_n;
double elapsed, max = 0.0; double elapsed, max = 0.0;
struct timespec start, end; struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
/* For each denominator q, we need to find the biggest numerator p for which /* For each denominator q, we need to find the biggest numerator p for which
* p/q<a/b, where a/b is 3/7 for this problem. So: * p/q<a/b, where a/b is 3/7 for this problem. So:
* pb<aq * pb<aq
* pb<=aq-1 * pb<=aq-1
* p<=(aq-1)/b * p<=(aq-1)/b
* So we can set p=(3*q-1)/7 (using integer division).*/ * So we can set p=(3*q-1)/7 (using integer division).*/
for(i = 2; i <= N; i++) for(i = 2; i <= N; i++)
{ {
j = (3 * i - 1) / 7; j = (3 * i - 1) / 7;
if((double)j / i > max) if((double)j / i > max)
{ {
n = j; n = j;
d = i; d = i;
max = (double)n / d; max = (double)n / d;
/* Reduce the fraction if it's not already reduced.*/ /* Reduce the fraction if it's not already reduced.*/
if(gcd(i, j) > 1) if(gcd(i, j) > 1)
{ {
n /= gcd(i, j); n /= gcd(i, j);
d /= gcd(i, j); d /= gcd(i, j);
} }
max_n = n; max_n = n;
} }
} }
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 71\n"); printf("Project Euler, Problem 71\n");
printf("Answer: %d\n", max_n); printf("Answer: %d\n", max_n);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0; return 0;
} }

View File

@ -8,6 +8,8 @@
* *
* How many elements would be contained in the set of reduced proper fractions for d 1,000,000?*/ * How many elements would be contained in the set of reduced proper fractions for d 1,000,000?*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <math.h> #include <math.h>
@ -18,37 +20,37 @@
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int i; int i;
int *primes; int *primes;
long int count = 0; long int count = 0;
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
if((primes = sieve(N)) == NULL) if((primes = sieve(N)) == NULL)
{ {
fprintf(stderr, "Error! Sieve function returned NULL\n"); fprintf(stderr, "Error! Sieve function returned NULL\n");
return 1; return 1;
} }
/* For any denominator d, the number of reduced proper fractions is /* For any denominator d, the number of reduced proper fractions is
* the number of fractions n/d where gcd(n, d)=1, which is the definition * the number of fractions n/d where gcd(n, d)=1, which is the definition
* of Euler's Totient Function phi. It's sufficient to calculate phi for each * of Euler's Totient Function phi. It's sufficient to calculate phi for each
* denominator and sum the value.*/ * denominator and sum the value.*/
for(i = 2; i < N; i++) for(i = 2; i < N; i++)
{ {
count += phi(i, primes); count += phi(i, primes);
} }
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 72\n"); printf("Project Euler, Problem 72\n");
printf("Answer: %ld\n", count); printf("Answer: %ld\n", count);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0; return 0;
} }

View File

@ -8,6 +8,8 @@
* *
* How many fractions lie between 1/3 and 1/2 in the sorted set of reduced proper fractions for d 12,000?*/ * How many fractions lie between 1/3 and 1/2 in the sorted set of reduced proper fractions for d 12,000?*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <time.h> #include <time.h>
@ -15,37 +17,37 @@
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int i, j, limit, count = 0; int i, j, limit, count = 0;
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
/* For each denominator q, we need to find the fractions p/q for which /* For each denominator q, we need to find the fractions p/q for which
* 1/3<p/q<1/2. For the lower limit, if p=q/3, then p/q=1/3, so we take * 1/3<p/q<1/2. For the lower limit, if p=q/3, then p/q=1/3, so we take
* p=q/3+1. For the upper limit, if p=q/2 p/q=1/2, so we take p=(q-1)/2.*/ * p=q/3+1. For the upper limit, if p=q/2 p/q=1/2, so we take p=(q-1)/2.*/
for(i = 2; i <= 12000; i++) for(i = 2; i <= 12000; i++)
{ {
limit = (i - 1) / 2; limit = (i - 1) / 2;
for(j = i / 3 + 1; j <= limit; j++) for(j = i / 3 + 1; j <= limit; j++)
{ {
/* Increment the counter if the current fraction is reduced.*/ /* Increment the counter if the current fraction is reduced.*/
if(gcd(j, i) == 1) if(gcd(j, i) == 1)
{ {
count++; count++;
} }
} }
} }
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 73\n"); printf("Project Euler, Problem 73\n");
printf("Answer: %d\n", count); printf("Answer: %d\n", count);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0; return 0;
} }

140
C/p074.c
View File

@ -20,6 +20,8 @@
* *
* How many chains, with a starting number below one million, contain exactly sixty non-repeating terms?*/ * How many chains, with a starting number below one million, contain exactly sixty non-repeating terms?*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <time.h> #include <time.h>
@ -34,99 +36,99 @@ int chains[N] = {0};
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int i, count = 0; int i, count = 0;
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
/* Simple brute force approach, for every number calculate /* Simple brute force approach, for every number calculate
* the length of the chain.*/ * the length of the chain.*/
for(i = 3; i < N; i++) for(i = 3; i < N; i++)
{ {
if(len_chain(i) == 60) if(len_chain(i) == 60)
{ {
count++; count++;
} }
} }
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 74\n"); printf("Project Euler, Problem 74\n");
printf("Answer: %d\n", count); printf("Answer: %d\n", count);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0; return 0;
} }
/* Recursively calculate the factorial, of a number, saving the result /* Recursively calculate the factorial, of a number, saving the result
* so that it can be reused later.*/ * so that it can be reused later.*/
int factorial(int n) int factorial(int n)
{ {
if(n == 0 || n == 1) if(n == 0 || n == 1)
{ {
return 1; return 1;
} }
else if(factorials[n] != 0) else if(factorials[n] != 0)
{ {
return factorials[n]; return factorials[n];
} }
else else
{ {
factorials[n]=n*factorial(n-1); factorials[n]=n*factorial(n-1);
return factorials[n]; return factorials[n];
} }
} }
int len_chain(int n) int len_chain(int n)
{ {
int i, count = 0, finished = 0, value, tmp; int i, count = 0, finished = 0, value, tmp;
int chain[60]; int chain[60];
value = n; value = n;
chain[count] = value; chain[count] = value;
while(!finished) while(!finished)
{ {
tmp = 0; tmp = 0;
count++; count++;
/* Generate the next number of the chain by taking /* Generate the next number of the chain by taking
* the digits of the current value, calculating the * the digits of the current value, calculating the
* factorials and adding them.*/ * factorials and adding them.*/
while(value != 0) while(value != 0)
{ {
tmp += factorial(value % 10); tmp += factorial(value % 10);
value /= 10; value /= 10;
} }
/* If the chain length for the new value has already been /* If the chain length for the new value has already been
* calculated before, use the saved value (only chains for * calculated before, use the saved value (only chains for
* values smaller than N are saved).*/ * values smaller than N are saved).*/
if(tmp < N && chains[tmp] != 0) if(tmp < N && chains[tmp] != 0)
{ {
return count + chains[tmp]; return count + chains[tmp];
} }
value = tmp; value = tmp;
/* If the current value is already present in the chain, /* If the current value is already present in the chain,
* the chain is finished.*/ * the chain is finished.*/
for(i = 0; i < count; i++) for(i = 0; i < count; i++)
{ {
if(chain[i] == value) if(chain[i] == value)
{ {
finished = 1; finished = 1;
} }
} }
chain[count] = value; chain[count] = value;
} }
chains[n] = count; chains[n] = count;
return count; return count;
} }

128
C/p075.c
View File

@ -15,6 +15,8 @@
* *
* Given that L is the length of the wire, for how many values of L 1,500,000 can exactly one integer sided right angle triangle be formed?*/ * Given that L is the length of the wire, for how many values of L 1,500,000 can exactly one integer sided right angle triangle be formed?*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <time.h> #include <time.h>
@ -24,79 +26,79 @@
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int i, a, b, c, tmpa, tmpb, tmpc, m, n, count = 0; int i, a, b, c, tmpa, tmpb, tmpc, m, n, count = 0;
int *l; int *l;
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
if((l = (int *)calloc(N + 1, sizeof(int))) == NULL) if((l = (int *)calloc(N + 1, sizeof(int))) == NULL)
{ {
fprintf(stderr, "Error while allocating memory\n"); fprintf(stderr, "Error while allocating memory\n");
return 1; return 1;
} }
/* Generate all Pythagorean triplets using Euclid's algorithm: /* Generate all Pythagorean triplets using Euclid's algorithm:
* For m>=2 and n<m: * For m>=2 and n<m:
* a=m*m-n*n * a=m*m-n*n
* b=2*m*n * b=2*m*n
* c=m*m+n*n * c=m*m+n*n
* This gives a primitive triple if gcd(m, n)=1 and exactly one * This gives a primitive triple if gcd(m, n)=1 and exactly one
* of m and n is odd. To generate all the triples, generate all * of m and n is odd. To generate all the triples, generate all
* the primitive one and multiply them by i=2,3, ..., n until the * the primitive one and multiply them by i=2,3, ..., n until the
* perimeter is larger than the limit. The limit for m is 865, because * perimeter is larger than the limit. The limit for m is 865, because
* when m=866 even with the smaller n (i.e. 1) the perimeter is greater * when m=866 even with the smaller n (i.e. 1) the perimeter is greater
* than the given limit.*/ * than the given limit.*/
for(m = 2; m < 866; m++) for(m = 2; m < 866; m++)
{ {
for(n = 1; n < m; n++) for(n = 1; n < m; n++)
{ {
if(gcd(m, n) == 1 && ((m % 2 == 0 && n % 2 != 0) || (m % 2 != 0 && n % 2 == 0))) if(gcd(m, n) == 1 && ((m % 2 == 0 && n % 2 != 0) || (m % 2 != 0 && n % 2 == 0)))
{
a = m * m - n * n;
b = 2 * m * n;
c = m * m + n * n;
if(a + b + c <= N)
{ {
l[a+b+c]++; a = m * m - n * n;
b = 2 * m * n;
c = m * m + n * n;
if(a + b + c <= N)
{
l[a+b+c]++;
}
i = 2;
tmpa = i * a;
tmpb = i * b;
tmpc = i * c;
while(tmpa + tmpb + tmpc <= N)
{
l[tmpa+tmpb+tmpc]++;
i++;
tmpa = i * a;
tmpb = i * b;
tmpc = i * c;
}
} }
}
}
i = 2; for(i = 0; i <= N; i++)
tmpa = i * a; {
tmpb = i * b; if(l[i] == 1)
tmpc = i * c; count++;
}
while(tmpa + tmpb + tmpc <= N) free(l);
{
l[tmpa+tmpb+tmpc]++;
i++; clock_gettime(CLOCK_MONOTONIC, &end);
tmpa = i * a;
tmpb = i * b;
tmpc = i * c;
}
}
}
}
for(i = 0; i <= N; i++) elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
{
if(l[i] == 1)
count++;
}
free(l); printf("Project Euler, Problem 75\n");
printf("Answer: %d\n", count);
clock_gettime(CLOCK_MONOTONIC, &end); printf("Elapsed time: %.9lf seconds\n", elapsed);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; return 0;
printf("Project Euler, Problem 75\n");
printf("Answer: %d\n", count);
printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0;
} }

View File

@ -9,6 +9,8 @@
* *
* How many different ways can one hundred be written as a sum of at least two positive integers?*/ * How many different ways can one hundred be written as a sum of at least two positive integers?*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <time.h> #include <time.h>
@ -16,34 +18,34 @@
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int n; int n;
long int *partitions; long int *partitions;
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
if((partitions = (long int *)calloc(100, sizeof(long int))) == NULL) if((partitions = (long int *)calloc(100, sizeof(long int))) == NULL)
{ {
fprintf(stderr, "Error while allocating memory\n"); fprintf(stderr, "Error while allocating memory\n");
return 1; return 1;
} }
/* The number of ways a number can be written as a sum is given by the partition function /* The number of ways a number can be written as a sum is given by the partition function
* (-1 because the partition function includes also the number itself). * (-1 because the partition function includes also the number itself).
* The function is implemented in projecteuler.c*/ * The function is implemented in projecteuler.c*/
n = partition_fn(100, partitions, -1) - 1; n = partition_fn(100, partitions, -1) - 1;
free(partitions); free(partitions);
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 76\n"); printf("Project Euler, Problem 76\n");
printf("Answer: %d\n", n); printf("Answer: %d\n", n);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0; return 0;
} }

View File

@ -8,6 +8,8 @@
* *
* What is the first value which can be written as the sum of primes in over five thousand different ways?*/ * What is the first value which can be written as the sum of primes in over five thousand different ways?*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <math.h> #include <math.h>
@ -20,64 +22,64 @@ int primes[100];
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int i, j, n; int i, j, n;
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
/* Generate a list of the first 100 primes.*/ /* Generate a list of the first 100 primes.*/
for(i = 0, j = 0; j < 100; i++) for(i = 0, j = 0; j < 100; i++)
{ {
if(is_prime(i)) if(is_prime(i))
{ {
primes[j++] = i; primes[j++] = i;
} }
} }
i = 1; i = 1;
/* Use a function to count the number of prime partitions for /* Use a function to count the number of prime partitions for
* each number >= 2 until the one that can be written in over * each number >= 2 until the one that can be written in over
* 5000 ways is found.*/ * 5000 ways is found.*/
while((n = count(0, 0, 0, ++i)) <= 5000); while((n = count(0, 0, 0, ++i)) <= 5000);
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 77\n"); printf("Project Euler, Problem 77\n");
printf("Answer: %d\n", i); printf("Answer: %d\n", i);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0; return 0;
} }
/* Function using a simple recursive brute force approach /* Function using a simple recursive brute force approach
* to find all the partitions.*/ * to find all the partitions.*/
int count(int value, int n, int i, int target) int count(int value, int n, int i, int target)
{ {
int j; int j;
for(j = i; j < 100; j++) for(j = i; j < 100; j++)
{ {
value += primes[j]; value += primes[j];
if(value == target) if(value == target)
{ {
return n + 1; return n + 1;
} }
else if(value > target) else if(value > target)
{ {
return n; return n;
} }
else else
{ {
n = count(value, n, j, target); n = count(value, n, j, target);
value -= primes[j]; value -= primes[j];
} }
} }
return n; return n;
} }

View File

@ -11,6 +11,8 @@
* *
* Find the least value of n for which p(n) is divisible by one million.*/ * Find the least value of n for which p(n) is divisible by one million.*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <time.h> #include <time.h>
@ -20,25 +22,25 @@
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int i = -1; int i = -1;
long int partitions[N] = {0}; long int partitions[N] = {0};
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
/* Using the partition function to calculate the number of partitions, /* Using the partition function to calculate the number of partitions,
* giving the result modulo N.*/ * giving the result modulo N.*/
while(partition_fn(++i, partitions, N) != 0); while(partition_fn(++i, partitions, N) != 0);
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 78\n"); printf("Project Euler, Problem 78\n");
printf("Answer: %d\n", i); printf("Answer: %d\n", i);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0; return 0;
} }

274
C/p079.c
View File

@ -6,6 +6,8 @@
* Given that the three characters are always asked for in order, analyse the file so as to determine the shortest possible * Given that the three characters are always asked for in order, analyse the file so as to determine the shortest possible
* secret passcode of unknown length.*/ * secret passcode of unknown length.*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <time.h> #include <time.h>
@ -16,174 +18,174 @@ int check_passcode(int **passcode, int len, int **logins, int n);
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int i, j, keylog, len = 4, found = 0, digits[10] = {0}, passcode_digits[10] = {0}, **passcode, **logins; int i, j, keylog, len = 4, found = 0, digits[10] = {0}, passcode_digits[10] = {0}, **passcode, **logins;
char line[5]; char line[5];
FILE *fp; FILE *fp;
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
if((fp = fopen("keylog.txt", "r")) == NULL) if((fp = fopen("keylog.txt", "r")) == NULL)
{ {
fprintf(stderr, "Error while opening file %s\n", "keylog.txt"); fprintf(stderr, "Error while opening file %s\n", "keylog.txt");
return 1; return 1;
} }
if((logins = (int **)malloc(50*sizeof(int*))) == NULL) if((logins = (int **)malloc(50*sizeof(int*))) == NULL)
{ {
fprintf(stderr, "Error while allocating memory\n"); fprintf(stderr, "Error while allocating memory\n");
return 1; return 1;
} }
for(i = 0; i < 50; i++) for(i = 0; i < 50; i++)
{ {
if((logins[i] = (int *)malloc(3*sizeof(int))) == NULL) if((logins[i] = (int *)malloc(3*sizeof(int))) == NULL)
{ {
fprintf(stderr, "Error while allocating memory\n");
return 1;
}
}
i = 0;
while(fscanf(fp, "%s", line) != EOF)
{
j = 2;
keylog = atoi(line);
while(keylog > 0)
{
logins[i][j--] = keylog % 10;
/* Check which digits are present in the login attempts.*/
digits[keylog%10]++;
keylog /= 10;
}
i++;
}
fclose(fp);
j = 0;
for(i = 0; i < 10; i++)
{
/* To generate the passcode, only use the digits present in the
* login attempts.*/
if(digits[i] > 0)
{
passcode_digits[j++] = i;
}
}
while(!found)
{
if((passcode = (int **)malloc(len*sizeof(int *))) == NULL)
{
fprintf(stderr, "Error while allocating memory\n");
return 1;
}
for(i = 0; i < len; i++)
{
if((passcode[i] = (int *)malloc(sizeof(int))) == NULL)
{
fprintf(stderr, "Error while allocating memory\n"); fprintf(stderr, "Error while allocating memory\n");
return 1; return 1;
} }
/* For the current length, generate the first passcode with the }
* digits in order.*/
*passcode[i] = passcode_digits[i];
}
/* Check if the passcode is compatible with the login attempts.*/ i = 0;
if(check_passcode(passcode, len, logins, 50))
{
found = 1;
break;
}
/* For the given length, check every permutation until the correct while(fscanf(fp, "%s", line) != EOF)
* passcode has been found, or all the permutations have been tried.*/ {
while(next_permutation((void **)passcode, len, compare) != -1) j = 2;
{ keylog = atoi(line);
if(check_passcode(passcode, len, logins, 50))
{
printf("Project Euler, Problem 79\n");
printf("Answer: ");
for(i = 0; i < len; i++)
printf("%d", *passcode[i]);
printf("\n");
while(keylog > 0)
{
logins[i][j--] = keylog % 10;
/* Check which digits are present in the login attempts.*/
digits[keylog%10]++;
keylog /= 10;
}
i++;
}
fclose(fp);
j = 0;
for(i = 0; i < 10; i++)
{
/* To generate the passcode, only use the digits present in the
* login attempts.*/
if(digits[i] > 0)
{
passcode_digits[j++] = i;
}
}
while(!found)
{
if((passcode = (int **)malloc(len*sizeof(int *))) == NULL)
{
fprintf(stderr, "Error while allocating memory\n");
return 1;
}
for(i = 0; i < len; i++)
{
if((passcode[i] = (int *)malloc(sizeof(int))) == NULL)
{
fprintf(stderr, "Error while allocating memory\n");
return 1;
}
/* For the current length, generate the first passcode with the
* digits in order.*/
*passcode[i] = passcode_digits[i];
}
/* Check if the passcode is compatible with the login attempts.*/
if(check_passcode(passcode, len, logins, 50))
{
found = 1; found = 1;
break; break;
} }
}
for(i = 0; i < len; i++) /* For the given length, check every permutation until the correct
{ * passcode has been found, or all the permutations have been tried.*/
free(passcode[i]); while(next_permutation((void **)passcode, len, compare) != -1)
} {
free(passcode); if(check_passcode(passcode, len, logins, 50))
{
printf("Project Euler, Problem 79\n");
printf("Answer: ");
for(i = 0; i < len; i++)
printf("%d", *passcode[i]);
printf("\n");
/* If the passcode has not yet been found, try a longer passcode.*/ found = 1;
len++; break;
} }
}
for(i = 0; i < 50; i++) for(i = 0; i < len; i++)
{ {
free(logins[i]); free(passcode[i]);
} }
free(passcode);
free(logins); /* If the passcode has not yet been found, try a longer passcode.*/
len++;
}
clock_gettime(CLOCK_MONOTONIC, &end); for(i = 0; i < 50; i++)
{
free(logins[i]);
}
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; free(logins);
printf("Elapsed time: %.9lf seconds\n", elapsed); clock_gettime(CLOCK_MONOTONIC, &end);
return 0; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0;
} }
int compare(void *a, void *b) int compare(void *a, void *b)
{ {
int *n1, *n2; int *n1, *n2;
n1 = (int *)a; n1 = (int *)a;
n2 = (int *)b; n2 = (int *)b;
return *n1 - *n2; return *n1 - *n2;
} }
int check_passcode(int **passcode, int len, int **logins, int n) int check_passcode(int **passcode, int len, int **logins, int n)
{ {
int i, j, k; int i, j, k;
/* For every login attempt, check if all the digits appear in the /* For every login attempt, check if all the digits appear in the
* passcode in the correct order. Return 0 if a login attempt * passcode in the correct order. Return 0 if a login attempt
* incompatible with the current passcode is found.*/ * incompatible with the current passcode is found.*/
for(i = 0; i < n; i++) for(i = 0; i < n; i++)
{ {
k = 0; k = 0;
for(j = 0; j < len; j++) for(j = 0; j < len; j++)
{ {
if(*passcode[j] == logins[i][k]) if(*passcode[j] == logins[i][k])
{
k++;
if(k == 3)
{ {
break; k++;
if(k == 3)
{
break;
}
} }
} }
}
if(k < 3) if(k < 3)
{ {
return 0; return 0;
} }
} }
return 1; return 1;
} }

View File

@ -6,6 +6,8 @@
* For the first one hundred natural numbers, find the total of the digital sums of the first one hundred decimal digits * For the first one hundred natural numbers, find the total of the digital sums of the first one hundred decimal digits
* for all the irrational square roots*/ * for all the irrational square roots*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <math.h> #include <math.h>
@ -16,65 +18,65 @@ int is_square(int n);
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int i, j, sum = 0; int i, j, sum = 0;
char sqrt_digits[104]; char sqrt_digits[104];
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
mpf_t sqrt; mpf_t sqrt;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
/* Set the precision to 333 bits (should be enough for 100 decimal digits.*/ /* Set the precision to 333 bits (should be enough for 100 decimal digits.*/
mpf_set_default_prec(333); mpf_set_default_prec(333);
mpf_init(sqrt); mpf_init(sqrt);
for(i = 2; i < 100; i++) for(i = 2; i < 100; i++)
{ {
if(is_square(i)) if(is_square(i))
{ {
continue; continue;
} }
/* Calculate the square root of the current number with the given precision /* Calculate the square root of the current number with the given precision
* and sum the digits to the total.*/ * and sum the digits to the total.*/
mpf_sqrt_ui(sqrt, i); mpf_sqrt_ui(sqrt, i);
gmp_sprintf(sqrt_digits, "%.101Ff\n", sqrt); gmp_sprintf(sqrt_digits, "%.101Ff\n", sqrt);
sum += (sqrt_digits[0] - '0'); sum += (sqrt_digits[0] - '0');
for(j = 2; j < 101; j++) for(j = 2; j < 101; j++)
{ {
sum += (sqrt_digits[j] - '0'); sum += (sqrt_digits[j] - '0');
} }
} }
mpf_clear(sqrt); mpf_clear(sqrt);
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 80\n"); printf("Project Euler, Problem 80\n");
printf("Answer: %d\n", sum); printf("Answer: %d\n", sum);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0; return 0;
} }
int is_square(int n) int is_square(int n)
{ {
int m; int m;
double p; double p;
p = sqrt(n); p = sqrt(n);
m = p; m = p;
if(p == m) if(p == m)
{ {
return 1; return 1;
} }
else else
{ {
return 0; return 0;
} }
} }

132
C/p081.c
View File

@ -10,6 +10,8 @@
* Find the minimal path sum, in matrix.txt, a 31K text file containing a 80 by 80 matrix, from the top left to the bottom right * Find the minimal path sum, in matrix.txt, a 31K text file containing a 80 by 80 matrix, from the top left to the bottom right
* by only moving right and down.*/ * by only moving right and down.*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <time.h> #include <time.h>
@ -19,92 +21,92 @@ int sum_paths(int **matrix, int m, int n);
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int i, j, dist; int i, j, dist;
int **matrix; int **matrix;
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
FILE *fp; FILE *fp;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
if((fp = fopen("matrix.txt", "r")) == NULL) if((fp = fopen("matrix.txt", "r")) == NULL)
{ {
fprintf(stderr, "Error while opening file %s\n", "matrix.txt"); fprintf(stderr, "Error while opening file %s\n", "matrix.txt");
return 1; return 1;
} }
if((matrix = (int **)malloc(80*sizeof(int *))) == NULL) if((matrix = (int **)malloc(80*sizeof(int *))) == NULL)
{ {
fprintf(stderr, "Error while allocating memory\n"); fprintf(stderr, "Error while allocating memory\n");
return 1; return 1;
} }
for(i = 0; i < 80; i++) for(i = 0; i < 80; i++)
{ {
if((matrix[i] = (int *)malloc(80*sizeof(int))) == NULL) if((matrix[i] = (int *)malloc(80*sizeof(int))) == NULL)
{ {
fprintf(stderr, "Error while allocating memory\n"); fprintf(stderr, "Error while allocating memory\n");
return 1; return 1;
} }
} }
for(i = 0; i < 80; i++) for(i = 0; i < 80; i++)
{ {
for(j = 0; j < 80; j++) for(j = 0; j < 80; j++)
{ {
fscanf(fp, "%d,", &matrix[i][j]); fscanf(fp, "%d,", &matrix[i][j]);
} }
} }
fclose(fp); fclose(fp);
dist = sum_paths(matrix, 80, 80); dist = sum_paths(matrix, 80, 80);
for(i = 0; i < 80; i++) for(i = 0; i < 80; i++)
{ {
free(matrix[i]); free(matrix[i]);
} }
free(matrix); free(matrix);
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 81\n"); printf("Project Euler, Problem 81\n");
printf("Answer: %d\n", dist); printf("Answer: %d\n", dist);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0; return 0;
} }
/* Get the shortest path starting from the bottom right corner /* Get the shortest path starting from the bottom right corner
* and going backwards.*/ * and going backwards.*/
int sum_paths(int **matrix, int m, int n) int sum_paths(int **matrix, int m, int n)
{ {
int i, j; int i, j;
for(i = m - 2; i >= 0; i--) for(i = m - 2; i >= 0; i--)
{ {
matrix[m-1][i] += matrix[m-1][i+1]; matrix[m-1][i] += matrix[m-1][i+1];
matrix[i][m-1] += matrix[i+1][m-1]; matrix[i][m-1] += matrix[i+1][m-1];
} }
for(i = m - 2; i >= 0; i--) for(i = m - 2; i >= 0; i--)
{ {
for(j = n - 2; j >= 0; j--) for(j = n - 2; j >= 0; j--)
{ {
if(matrix[i][j+1] > matrix[i+1][j]) if(matrix[i][j+1] > matrix[i+1][j])
{ {
matrix[i][j] += matrix[i+1][j]; matrix[i][j] += matrix[i+1][j];
} }
else else
{ {
matrix[i][j] += matrix[i][j+1]; matrix[i][j] += matrix[i][j+1];
} }
} }
} }
return matrix[0][0]; return matrix[0][0];
} }

134
C/p082.c
View File

@ -11,6 +11,8 @@
* *
* Find the minimal path sum, in matrix.txt, a 31K text file containing a 80 by 80 matrix, from the left column to the right column.*/ * Find the minimal path sum, in matrix.txt, a 31K text file containing a 80 by 80 matrix, from the left column to the right column.*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <time.h> #include <time.h>
@ -19,85 +21,85 @@
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int i, j, min_path=INT_MAX; int i, j, min_path=INT_MAX;
int **matrix, **distances; int **matrix, **distances;
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
FILE *fp; FILE *fp;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
if((fp = fopen("matrix.txt", "r")) == NULL) if((fp = fopen("matrix.txt", "r")) == NULL)
{ {
fprintf(stderr, "Error while opening file %s\n", "matrix.txt"); fprintf(stderr, "Error while opening file %s\n", "matrix.txt");
return 1; return 1;
} }
if((matrix = (int **)malloc(80*sizeof(int *))) == NULL || if((matrix = (int **)malloc(80*sizeof(int *))) == NULL ||
(distances = (int **)malloc(80*sizeof(int *))) == NULL) (distances = (int **)malloc(80*sizeof(int *))) == NULL)
{ {
fprintf(stderr, "Error while allocating memory\n"); fprintf(stderr, "Error while allocating memory\n");
return 1; return 1;
} }
for(i = 0; i < 80; i++) for(i = 0; i < 80; i++)
{ {
if((matrix[i] = (int *)malloc(80*sizeof(int))) == NULL || if((matrix[i] = (int *)malloc(80*sizeof(int))) == NULL ||
(distances[i] = (int *)malloc(80*sizeof(int))) == NULL) (distances[i] = (int *)malloc(80*sizeof(int))) == NULL)
{ {
fprintf(stderr, "Error while allocating memory\n"); fprintf(stderr, "Error while allocating memory\n");
return 1; return 1;
} }
} }
for(i = 0; i < 80; i++) for(i = 0; i < 80; i++)
{ {
for(j = 0; j < 80; j++) for(j = 0; j < 80; j++)
{ {
fscanf(fp, "%d,", &matrix[i][j]); fscanf(fp, "%d,", &matrix[i][j]);
} }
} }
fclose(fp); fclose(fp);
/* Use Dijkstra's algorithm starting from all possible nodes /* Use Dijkstra's algorithm starting from all possible nodes
* in the first column.*/ * in the first column.*/
for(i = 0; i < 80; i++) for(i = 0; i < 80; i++)
{ {
if(dijkstra(matrix, distances, 80, 80, 1, 0, i) == -1) if(dijkstra(matrix, distances, 80, 80, 1, 0, i) == -1)
{ {
fprintf(stderr, "Error! Dijkstra function returned -1\n"); fprintf(stderr, "Error! Dijkstra function returned -1\n");
return 1; return 1;
} }
/* For the current starting node, check if there is an ending node /* For the current starting node, check if there is an ending node
* with a smaller path cost than the current minimum.*/ * with a smaller path cost than the current minimum.*/
for(j = 0; j < 80; j++) for(j = 0; j < 80; j++)
{ {
if(distances[j][79] < min_path) if(distances[j][79] < min_path)
{ {
min_path = distances[j][79]; min_path = distances[j][79];
} }
} }
} }
for(i = 0; i < 80; i++) for(i = 0; i < 80; i++)
{ {
free(matrix[i]); free(matrix[i]);
free(distances[i]); free(distances[i]);
} }
free(matrix); free(matrix);
free(distances); free(distances);
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 82\n"); printf("Project Euler, Problem 82\n");
printf("Answer: %d\n", min_path); printf("Answer: %d\n", min_path);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0; return 0;
} }

110
C/p083.c
View File

@ -12,6 +12,8 @@
* Find the minimal path sum, in matrix.txt, a 31K text file containing a 80 by 80 matrix, * Find the minimal path sum, in matrix.txt, a 31K text file containing a 80 by 80 matrix,
* from the top left to the bottom right by moving left, right, up, and down.*/ * from the top left to the bottom right by moving left, right, up, and down.*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <time.h> #include <time.h>
@ -20,73 +22,73 @@
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int i, j, dist; int i, j, dist;
int **matrix, **distances; int **matrix, **distances;
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
FILE *fp; FILE *fp;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
if((fp = fopen("matrix.txt", "r")) == NULL) if((fp = fopen("matrix.txt", "r")) == NULL)
{ {
fprintf(stderr, "Error while opening file %s\n", "matrix.txt"); fprintf(stderr, "Error while opening file %s\n", "matrix.txt");
return 1; return 1;
} }
if((matrix = (int **)malloc(80*sizeof(int *))) == NULL || if((matrix = (int **)malloc(80*sizeof(int *))) == NULL ||
(distances = (int **)malloc(80*sizeof(int *))) == NULL) (distances = (int **)malloc(80*sizeof(int *))) == NULL)
{ {
fprintf(stderr, "Error while allocating memory\n"); fprintf(stderr, "Error while allocating memory\n");
return 1; return 1;
} }
for(i = 0; i < 80; i++) for(i = 0; i < 80; i++)
{ {
if((matrix[i] = (int *)malloc(80*sizeof(int))) == NULL || if((matrix[i] = (int *)malloc(80*sizeof(int))) == NULL ||
(distances[i] = (int *)malloc(80*sizeof(int))) == NULL) (distances[i] = (int *)malloc(80*sizeof(int))) == NULL)
{ {
fprintf(stderr, "Error while allocating memory\n"); fprintf(stderr, "Error while allocating memory\n");
return 1; return 1;
} }
} }
for(i = 0; i < 80; i++) for(i = 0; i < 80; i++)
{ {
for(j = 0; j < 80; j++) for(j = 0; j < 80; j++)
{ {
fscanf(fp, "%d,", &matrix[i][j]); fscanf(fp, "%d,", &matrix[i][j]);
} }
} }
fclose(fp); fclose(fp);
/* Use Dijkstra's algorithm to find the minimum path.*/ /* Use Dijkstra's algorithm to find the minimum path.*/
if(dijkstra(matrix, distances, 80, 80, 1, 1, 0) == -1) if(dijkstra(matrix, distances, 80, 80, 1, 1, 0) == -1)
{ {
fprintf(stderr, "Error! Dijkstra function returned -1\n"); fprintf(stderr, "Error! Dijkstra function returned -1\n");
return 1; return 1;
} }
dist = distances[79][79]; dist = distances[79][79];
for(i = 0; i < 80; i++) for(i = 0; i < 80; i++)
{ {
free(matrix[i]); free(matrix[i]);
free(distances[i]); free(distances[i]);
} }
free(matrix); free(matrix);
free(distances); free(distances);
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 83\n"); printf("Project Euler, Problem 83\n");
printf("Answer: %d\n", dist); printf("Answer: %d\n", dist);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0; return 0;
} }

417
C/p084.c
View File

@ -66,6 +66,8 @@
* *
* If, instead of using two 6-sided dice, two 4-sided dice are used, find the six-digit modal string.*/ * If, instead of using two 6-sided dice, two 4-sided dice are used, find the six-digit modal string.*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
@ -75,8 +77,9 @@
/* Define the squares, the type of Community Chest cards and the type of Chance cards.*/ /* Define the squares, the type of Community Chest cards and the type of Chance cards.*/
typedef enum {GO, A1, CC1, A2, T1, R1, B1, CH1, B2, B3, JAIL, typedef enum {GO, A1, CC1, A2, T1, R1, B1, CH1, B2, B3, JAIL,
C1, U1, C2, C3, R2, D1, CC2, D2, D3, FP, E1, CH2, E2, E3, R3, F1, C1, U1, C2, C3, R2, D1, CC2, D2, D3, FP, E1, CH2, E2, E3, R3, F1,
F2, U2, F3, G2J, G1, G2, CC3, G3, R4, CH3, H1, T2, H2} squares; F2, U2, F3, G2J, G1, G2, CC3, G3, R4, CH3, H1, T2, H2
} squares;
typedef enum {GO_cc, JAIL_cc, NOP_cc} cc_card; typedef enum {GO_cc, JAIL_cc, NOP_cc} cc_card;
typedef enum {GO_ch, JAIL_ch, C1_ch, E3_ch, H2_ch, R1_ch, R_ch1, R_ch2, U_ch, M3, NOP_ch} ch_card; typedef enum {GO_ch, JAIL_ch, C1_ch, E3_ch, H2_ch, R1_ch, R_ch1, R_ch2, U_ch, M3, NOP_ch} ch_card;
@ -86,261 +89,261 @@ void play(long int *count_squares);
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int i, j, max, max_i; int i, j, max, max_i;
long int count_squares[40] = {0}; long int count_squares[40] = {0};
char sq[3], *res; char sq[3], *res;
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
srand(time(NULL)); srand(time(NULL));
/* Play Monopoly.*/ /* Play Monopoly.*/
play(count_squares); play(count_squares);
if((res = (char *)malloc(7*sizeof(char))) == NULL) if((res = (char *)malloc(7*sizeof(char))) == NULL)
{ {
fprintf(stderr, "Error while allocating memory\n"); fprintf(stderr, "Error while allocating memory\n");
return 1; return 1;
} }
/* Find the three squares with maximum count.*/ /* Find the three squares with maximum count.*/
for(i = 0; i < 3; i++) for(i = 0; i < 3; i++)
{ {
max = -1; max = -1;
for(j = 0; j < 40; j++) for(j = 0; j < 40; j++)
{ {
if(count_squares[j] > max) if(count_squares[j] > max)
{ {
max = count_squares[j]; max = count_squares[j];
max_i = j; max_i = j;
} }
} }
if(max_i < 10) if(max_i < 10)
{ {
sprintf(sq, "0%d", max_i); sprintf(sq, "0%d", max_i);
} }
else else
{ {
sprintf(sq, "%d", max_i); sprintf(sq, "%d", max_i);
} }
res = strcat(res, sq); res = strcat(res, sq);
count_squares[max_i] = 0; count_squares[max_i] = 0;
} }
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 84\n"); printf("Project Euler, Problem 84\n");
printf("Answer: %s\n", res); printf("Answer: %s\n", res);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
free(res); free(res);
return 0; return 0;
} }
/* Shuffle the Community Chest cards.*/ /* Shuffle the Community Chest cards.*/
void shuffle_cc(cc_card cc[]) void shuffle_cc(cc_card cc[])
{ {
int i; int i;
cc_card c; cc_card c;
for(i = 0; i < 16; i++) for(i = 0; i < 16; i++)
{ {
cc[i] = NOP_cc; cc[i] = NOP_cc;
} }
c = GO_cc; c = GO_cc;
do do
{ {
do do
{ {
i = rand() % 16; i = rand() % 16;
}while(cc[i] != NOP_cc); } while(cc[i] != NOP_cc);
cc[i] = c; cc[i] = c;
c++; c++;
}while(c < NOP_cc); } while(c < NOP_cc);
} }
/* Shuffle the Chance cards.*/ /* Shuffle the Chance cards.*/
void shuffle_ch(ch_card ch[]) void shuffle_ch(ch_card ch[])
{ {
int i; int i;
ch_card h; ch_card h;
for(i = 0; i < 16; i++) for(i = 0; i < 16; i++)
{ {
ch[i] = NOP_ch; ch[i] = NOP_ch;
} }
h = GO_ch; h = GO_ch;
do do
{ {
do do
{ {
i = rand() % 16; i = rand() % 16;
}while(ch[i] != NOP_ch); } while(ch[i] != NOP_ch);
ch[i] = h; ch[i] = h;
h++; h++;
}while(h < NOP_ch); } while(h < NOP_ch);
} }
/* Function to play Monopoly, rolling the dice N times.*/ /* Function to play Monopoly, rolling the dice N times.*/
void play(long int *count_squares) void play(long int *count_squares)
{ {
int i, d1, d2, cc_i, ch_i, count_doubles; int i, d1, d2, cc_i, ch_i, count_doubles;
squares current; squares current;
cc_card cc[16]; cc_card cc[16];
ch_card ch[16]; ch_card ch[16];
/* Start from GO.*/ /* Start from GO.*/
current = GO; current = GO;
count_squares[GO]++; count_squares[GO]++;
cc_i = 0; cc_i = 0;
ch_i = 0; ch_i = 0;
count_doubles = 0; count_doubles = 0;
shuffle_cc(cc); shuffle_cc(cc);
shuffle_ch(ch); shuffle_ch(ch);
for(i = 0; i < N; i++) for(i = 0; i < N; i++)
{ {
/* Roll the dice.*/ /* Roll the dice.*/
d1 = 1 + rand() % 4; d1 = 1 + rand() % 4;
d2 = 1 + rand() % 4; d2 = 1 + rand() % 4;
/* Check if it's a double. Increment the doubles counter if yes, /* Check if it's a double. Increment the doubles counter if yes,
* reset it if no.*/ * reset it if no.*/
if(d1 == d2) if(d1 == d2)
{ {
count_doubles++; count_doubles++;
} }
else else
{ {
count_doubles=0; count_doubles=0;
} }
/* If this is the third double in a row, go to JAIL and reset /* If this is the third double in a row, go to JAIL and reset
* the doubles counter.*/ * the doubles counter.*/
if(count_doubles == 3) if(count_doubles == 3)
{ {
current = JAIL;
count_doubles = 0;
}
else
{
/* Move based on the dice roll.*/
current = (current + d1 + d2) % 40;
/* If you get to the Go to JAIL square, go to JAIL.*/
if(current == G2J)
{
current = JAIL; current = JAIL;
} count_doubles = 0;
/* If you get to one of the Community Chest squares, get a CC card.*/ }
else if(current == CC1 || current == CC2 || current == CC3) else
{ {
/* Go to GO.*/ /* Move based on the dice roll.*/
if(cc[cc_i] == GO_cc) current = (current + d1 + d2) % 40;
{
current = GO;
}
/* Go to JAIL.*/
else if(cc[cc_i] == JAIL_cc)
{
current = JAIL;
}
/* Otherwise do nothing.*/
cc_i = (cc_i + 1) % 16; /* If you get to the Go to JAIL square, go to JAIL.*/
} if(current == G2J)
/* If you get to one of the Chance squares, get a CH card.*/
else if(current == CH1 || current == CH2 || current == CH3)
{
/* Go to GO.*/
if(ch[ch_i] == GO_ch)
{ {
current = GO; current = JAIL;
} }
/* Go to JAIL.*/ /* If you get to one of the Community Chest squares, get a CC card.*/
else if(ch[ch_i] == JAIL_ch) else if(current == CC1 || current == CC2 || current == CC3)
{ {
current = JAIL; /* Go to GO.*/
} if(cc[cc_i] == GO_cc)
/* Go to C1.*/ {
else if(ch[ch_i] == C1_ch) current = GO;
{ }
current = C1; /* Go to JAIL.*/
} else if(cc[cc_i] == JAIL_cc)
/* Go to E3.*/ {
else if(ch[ch_i] == E3_ch) current = JAIL;
{ }
current = E3; /* Otherwise do nothing.*/
}
/* Go to H2.*/
else if(ch[ch_i] == H2_ch)
{
current = H2;
}
/* Go to R1.*/
else if(ch[ch_i] == R1_ch)
{
current = R1;
}
/* Go to the next Railway station.*/
else if(ch[ch_i] == R_ch1 || ch[ch_i] == R_ch2)
{
do
{
current = (current + 1) % 40;
}while(current != R1 && current != R2 && current != R3 && current != R4);
}
/* Go to the next Utility company.*/
else if(ch[ch_i] == U_ch)
{
do
{
current = (current + 1) % 40;
}while(current != U1 && current != U2);
}
/* Go back three squares.*/
else if(ch[ch_i] == M3)
{
current = current - 3;
/* If you get to Community Chest 3, get a card.*/ cc_i = (cc_i + 1) % 16;
if(current == CC3)
{
if(cc[cc_i] == GO_cc)
{
current = GO;
}
else if(cc[cc_i] == JAIL_cc)
{
current=JAIL;
}
cc_i = (cc_i + 1) % 16;
}
} }
/* If you get to one of the Chance squares, get a CH card.*/
else if(current == CH1 || current == CH2 || current == CH3)
{
/* Go to GO.*/
if(ch[ch_i] == GO_ch)
{
current = GO;
}
/* Go to JAIL.*/
else if(ch[ch_i] == JAIL_ch)
{
current = JAIL;
}
/* Go to C1.*/
else if(ch[ch_i] == C1_ch)
{
current = C1;
}
/* Go to E3.*/
else if(ch[ch_i] == E3_ch)
{
current = E3;
}
/* Go to H2.*/
else if(ch[ch_i] == H2_ch)
{
current = H2;
}
/* Go to R1.*/
else if(ch[ch_i] == R1_ch)
{
current = R1;
}
/* Go to the next Railway station.*/
else if(ch[ch_i] == R_ch1 || ch[ch_i] == R_ch2)
{
do
{
current = (current + 1) % 40;
} while(current != R1 && current != R2 && current != R3 && current != R4);
}
/* Go to the next Utility company.*/
else if(ch[ch_i] == U_ch)
{
do
{
current = (current + 1) % 40;
} while(current != U1 && current != U2);
}
/* Go back three squares.*/
else if(ch[ch_i] == M3)
{
current = current - 3;
ch_i = (ch_i + 1) % 16; /* If you get to Community Chest 3, get a card.*/
} if(current == CC3)
} {
if(cc[cc_i] == GO_cc)
{
current = GO;
}
else if(cc[cc_i] == JAIL_cc)
{
current=JAIL;
}
/* Increase the counter for the current square.*/ cc_i = (cc_i + 1) % 16;
count_squares[current]++; }
} }
ch_i = (ch_i + 1) % 16;
}
}
/* Increase the counter for the current square.*/
count_squares[current]++;
}
} }

View File

@ -2,6 +2,8 @@
* *
* Although there exists no rectangular grid that contains exactly two million rectangles, find the area of the grid with the nearest solution.*/ * Although there exists no rectangular grid that contains exactly two million rectangles, find the area of the grid with the nearest solution.*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <math.h> #include <math.h>
@ -10,41 +12,41 @@
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int i, j, n, diff, min_diff = INT_MAX, area; int i, j, n, diff, min_diff = INT_MAX, area;
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
for(i = 1; i < 100; i++) for(i = 1; i < 100; i++)
{ {
for(j = 1; j <= i; j++) for(j = 1; j <= i; j++)
{ {
/* In a 2x3 grid, we can take rectangles of height 2 in 3 ways /* In a 2x3 grid, we can take rectangles of height 2 in 3 ways
* (two rectangles of height one and one of height 2). For the * (two rectangles of height one and one of height 2). For the
* width, can take 6 rectangles (3 of width 1, 2 of width 2 and * width, can take 6 rectangles (3 of width 1, 2 of width 2 and
* 1 of width 3). The total is 6x3=18 rectagles. * 1 of width 3). The total is 6x3=18 rectagles.
* Extending to mxn, we can take (m+m-1+m-2+...+1)x(n+n-1+n-2+...+1)= * Extending to mxn, we can take (m+m-1+m-2+...+1)x(n+n-1+n-2+...+1)=
* m(m+1)/2*n(n+1)/2=m(m+1)*n(n+1)/4 rectangles.*/ * m(m+1)/2*n(n+1)/2=m(m+1)*n(n+1)/4 rectangles.*/
n = ( i * (i + 1) * j * (j + 1)) / 4; n = ( i * (i + 1) * j * (j + 1)) / 4;
diff = abs(2000000 - n); diff = abs(2000000 - n);
if(diff < min_diff) if(diff < min_diff)
{ {
min_diff = diff; min_diff = diff;
area = i * j; area = i * j;
} }
} }
} }
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 85\n"); printf("Project Euler, Problem 85\n");
printf("Answer: %d\n", area); printf("Answer: %d\n", area);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0; return 0;
} }

View File

@ -9,6 +9,8 @@
* *
* Find the least value of M such that the number of solutions first exceeds one million.*/ * Find the least value of M such that the number of solutions first exceeds one million.*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <math.h> #include <math.h>
@ -16,41 +18,41 @@
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int a, b, c, count = 0; int a, b, c, count = 0;
double d, elapsed; double d, elapsed;
struct timespec start, end; struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
a = 0; a = 0;
while(count <= 1000000) while(count <= 1000000)
{ {
a++; a++;
for(b = 1; b <= a; b++) for(b = 1; b <= a; b++)
{ {
for(c = 1; c <= b; c++) for(c = 1; c <= b; c++)
{ {
/* Unfolding the cuboid, it's obvious that the shortest path /* Unfolding the cuboid, it's obvious that the shortest path
* is the hypotenuse of a triangle, and the catheti are the * is the hypotenuse of a triangle, and the catheti are the
* longest side of the cubois and the sum of the other two sides.*/ * longest side of the cubois and the sum of the other two sides.*/
d = sqrt(a*a+(b+c)*(b+c)); d = sqrt(a*a+(b+c)*(b+c));
if(d == (int)d) if(d == (int)d)
count++; count++;
} }
} }
} }
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 86\n"); printf("Project Euler, Problem 86\n");
printf("Answer: %d\n", a); printf("Answer: %d\n", a);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0; return 0;
} }

110
C/p087.c
View File

@ -8,6 +8,8 @@
* *
* How many numbers below fifty million can be expressed as the sum of a prime square, prime cube, and prime fourth power?*/ * How many numbers below fifty million can be expressed as the sum of a prime square, prime cube, and prime fourth power?*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <math.h> #include <math.h>
@ -23,71 +25,71 @@ int *primes;
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int count = 0; int count = 0;
int *numbers; int *numbers;
long int i, j, k, n; long int i, j, k, n;
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
/* Generate primes up to the square root of the limit.*/ /* Generate primes up to the square root of the limit.*/
if((primes = sieve(SQRT_N)) == NULL) if((primes = sieve(SQRT_N)) == NULL)
{ {
fprintf(stderr, "Error! Sieve function returned NULL\n"); fprintf(stderr, "Error! Sieve function returned NULL\n");
return 1; return 1;
} }
if((numbers = (int *)calloc(N, sizeof(int))) == NULL) if((numbers = (int *)calloc(N, sizeof(int))) == NULL)
{ {
fprintf(stderr, "Error while allocating memory\n"); fprintf(stderr, "Error while allocating memory\n");
return 1; return 1;
} }
/* If i>sqrt(n), i*i will be >n, so n won't be a sum of /* If i>sqrt(n), i*i will be >n, so n won't be a sum of
* a square, cube and fourth power.*/ * a square, cube and fourth power.*/
for(i = 2; i <= SQRT_N; i++) for(i = 2; i <= SQRT_N; i++)
{ {
/* If i is not prime, try next number.*/ /* If i is not prime, try next number.*/
if(primes[i]) if(primes[i])
{ {
/* If j>cubic_root(n), j*j*j will be >n.*/ /* If j>cubic_root(n), j*j*j will be >n.*/
for(j = 2; j <= RAD3_N; j++) for(j = 2; j <= RAD3_N; j++)
{
if(primes[j])
{ {
/* If k>fourth_root(n), k*k*k*k will be >n.*/ if(primes[j])
for(k = 2; k <= RAD4_N; k++) {
{ /* If k>fourth_root(n), k*k*k*k will be >n.*/
if(primes[k]) for(k = 2; k <= RAD4_N; k++)
{ {
n = i * i + j * j * j + k * k * k * k; if(primes[k])
{
n = i * i + j * j * j + k * k * k * k;
/* Check if the number found is lower than the limit, /* Check if the number found is lower than the limit,
* and make sure it hasn't been found before.*/ * and make sure it hasn't been found before.*/
if(n < N && numbers[n] == 0) if(n < N && numbers[n] == 0)
{ {
count++; count++;
numbers[n] = 1; numbers[n] = 1;
} }
} }
} }
}
} }
} }
} }
}
free(primes); free(primes);
free(numbers); free(numbers);
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 87\n"); printf("Project Euler, Problem 87\n");
printf("Answer: %d\n", count); printf("Answer: %d\n", count);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0; return 0;
} }

124
C/p089.c
View File

@ -19,6 +19,8 @@
* *
* Note: You can assume that all the Roman numerals in the file contain no more than four consecutive identical units.*/ * Note: You can assume that all the Roman numerals in the file contain no more than four consecutive identical units.*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
@ -28,81 +30,81 @@ int reduce(char *numeral, int l);
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int i, l, count = 0, count_reduced = 0; int i, l, count = 0, count_reduced = 0;
char *numerals[1000]; char *numerals[1000];
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
FILE *fp; FILE *fp;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
if((fp = fopen("roman.txt", "r")) == NULL) if((fp = fopen("roman.txt", "r")) == NULL)
{ {
fprintf(stderr, "Error while opening file %s\n", "roman.txt"); fprintf(stderr, "Error while opening file %s\n", "roman.txt");
return 1; return 1;
} }
/* Get the roman numerals from file, for each find its length, then /* Get the roman numerals from file, for each find its length, then
* reduce it and find the new length. At the end, find the difference * reduce it and find the new length. At the end, find the difference
* of the two lengths.*/ * of the two lengths.*/
for(i = 0; i < 1000; i++) for(i = 0; i < 1000; i++)
{ {
fscanf(fp, "%ms", &numerals[i]); fscanf(fp, "%ms", &numerals[i]);
l = strlen(numerals[i]); l = strlen(numerals[i]);
count += l; count += l;
l = reduce(numerals[i], l); l = reduce(numerals[i], l);
count_reduced += l; count_reduced += l;
free(numerals[i]); free(numerals[i]);
} }
fclose(fp); fclose(fp);
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 89\n"); printf("Project Euler, Problem 89\n");
printf("Answer: %d\n", count-count_reduced); printf("Answer: %d\n", count-count_reduced);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0; return 0;
} }
int reduce(char *numeral, int l) int reduce(char *numeral, int l)
{ {
/* DCCCC = CM.*/ /* DCCCC = CM.*/
if(strstr(numeral, "DCCCC") != NULL) if(strstr(numeral, "DCCCC") != NULL)
{ {
l -= 3; l -= 3;
} }
/* CCCC = CD.*/ /* CCCC = CD.*/
else if(strstr(numeral, "CCCC") != NULL) else if(strstr(numeral, "CCCC") != NULL)
{ {
l -= 2; l -= 2;
} }
/* LXXXX = XC.*/ /* LXXXX = XC.*/
if(strstr(numeral, "LXXXX") != NULL) if(strstr(numeral, "LXXXX") != NULL)
{ {
l -= 3; l -= 3;
} }
/* XXXX = XL.*/ /* XXXX = XL.*/
else if(strstr(numeral, "XXXX") != NULL) else if(strstr(numeral, "XXXX") != NULL)
{ {
l -= 2; l -= 2;
} }
/* VIIII = IX.*/ /* VIIII = IX.*/
if(strstr(numeral, "VIIII") != NULL) if(strstr(numeral, "VIIII") != NULL)
{ {
l -= 3; l -= 3;
} }
/* IIII = IV.*/ /* IIII = IV.*/
else if(strstr(numeral, "IIII") != NULL) else if(strstr(numeral, "IIII") != NULL)
{ {
l -= 2; l -= 2;
} }
return l; return l;
} }

View File

@ -10,6 +10,8 @@
* *
* How many starting numbers below ten million will arrive at 89?*/ * How many starting numbers below ten million will arrive at 89?*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <time.h> #include <time.h>
@ -22,63 +24,63 @@ int chain(int n);
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int i, count = 0; int i, count = 0;
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
for(i = 1; i < N; i++) for(i = 1; i < N; i++)
{ {
/* Simply create a chain for each number and check if it ends at 89, saving /* Simply create a chain for each number and check if it ends at 89, saving
* the result so it can be reused.*/ * the result so it can be reused.*/
if((chains[i] = chain(i)) == 89) if((chains[i] = chain(i)) == 89)
{ {
count++; count++;
} }
} }
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 92\n"); printf("Project Euler, Problem 92\n");
printf("Answer: %d\n", count); printf("Answer: %d\n", count);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0; return 0;
} }
/* Recursively find the chain for n.*/ /* Recursively find the chain for n.*/
int chain(int n) int chain(int n)
{ {
int tmp = 0, digit; int tmp = 0, digit;
/* If n=1 or n=89, we reached the end of the chain.*/ /* If n=1 or n=89, we reached the end of the chain.*/
if(n == 1) if(n == 1)
{ {
return 1; return 1;
} }
if(n == 89) if(n == 89)
{ {
return 89; return 89;
} }
/* If the chain for the current n has already been found, /* If the chain for the current n has already been found,
* return the value.*/ * return the value.*/
if(chains[n] != 0) if(chains[n] != 0)
{ {
return chains[n]; return chains[n];
} }
while(n > 0) while(n > 0)
{ {
digit = n % 10; digit = n % 10;
tmp += digit * digit; tmp += digit * digit;
n /= 10; n /= 10;
} }
return chain(tmp); return chain(tmp);
} }

150
C/p095.c
View File

@ -12,6 +12,8 @@
* *
* Find the smallest member of the longest amicable chain with no element exceeding one million.*/ * Find the smallest member of the longest amicable chain with no element exceeding one million.*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <math.h> #include <math.h>
@ -26,99 +28,99 @@ int divisors[N] = {0};
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int i, min = 0, min_tmp, length, l_max = 0; int i, min = 0, min_tmp, length, l_max = 0;
int chain[100]; int chain[100];
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
for(i = 4; i <= N; i++) for(i = 4; i <= N; i++)
{ {
/* Calculate the divisors of i and save it. Ii is equal to the sum of its proper divisors, /* Calculate the divisors of i and save it. Ii is equal to the sum of its proper divisors,
* the length of the chain is 1 and we don't need to check it.*/ * the length of the chain is 1 and we don't need to check it.*/
if((divisors[i] = sum_of_divisors(i, 1)) == i) if((divisors[i] = sum_of_divisors(i, 1)) == i)
{ {
continue; continue;
} }
else else
{ {
min_tmp = i; min_tmp = i;
length = sociable_chain(i, chain, 0, &min_tmp); length = sociable_chain(i, chain, 0, &min_tmp);
} }
if(length > l_max) if(length > l_max)
{ {
l_max = length; l_max = length;
min = min_tmp; min = min_tmp;
} }
} }
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 95\n"); printf("Project Euler, Problem 95\n");
printf("Answer: %d\n", min); printf("Answer: %d\n", min);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0; return 0;
} }
/* Function to recursively find the length of the chain.*/ /* Function to recursively find the length of the chain.*/
int sociable_chain(int i, int *chain, int l, int *min) int sociable_chain(int i, int *chain, int l, int *min)
{ {
int n; int n;
/* Save current number in the chain.*/ /* Save current number in the chain.*/
chain[l] = i; chain[l] = i;
/* If we reached 1, the chain will never go anywhere.*/ /* If we reached 1, the chain will never go anywhere.*/
if(i == 1) if(i == 1)
{ {
return -1; return -1;
} }
/* Calculate the divisors of i, or retrieve the value if previously calculated.*/ /* Calculate the divisors of i, or retrieve the value if previously calculated.*/
if(divisors[i] != 0) if(divisors[i] != 0)
{ {
n = divisors[i]; n = divisors[i];
} }
else else
{ {
n = sum_of_divisors(i, 1); n = sum_of_divisors(i, 1);
divisors[i] = n; divisors[i] = n;
} }
/* We are looking for chain where no value is greater than 1000000.*/ /* We are looking for chain where no value is greater than 1000000.*/
if(n > N) if(n > N)
{ {
return -1; return -1;
} }
/* If the next number in the chain is equal to the starting one, the chain is finished.*/ /* If the next number in the chain is equal to the starting one, the chain is finished.*/
if(n == chain[0]) if(n == chain[0])
{ {
return l + 1; return l + 1;
} }
/* Check if n is equal to another value of the chain different from start. If it is, the /* Check if n is equal to another value of the chain different from start. If it is, the
* chain is stuck in a loop that will not return to the starting number.*/ * chain is stuck in a loop that will not return to the starting number.*/
for(i = l; i > 0; i--) for(i = l; i > 0; i--)
{ {
if(n == chain[i]) if(n == chain[i])
{ {
return -1; return -1;
} }
} }
/* If the next value is smaller than the minimum value of the chain, /* If the next value is smaller than the minimum value of the chain,
* update the minimum.*/ * update the minimum.*/
if(n < *min) if(n < *min)
{ {
*min = n; *min = n;
} }
return sociable_chain(n, chain, l+1, min); return sociable_chain(n, chain, l+1, min);
} }

400
C/p096.c
View File

@ -25,6 +25,8 @@
* By solving all fifty puzzles find the sum of the 3-digit numbers found in the top left corner of each solution grid; * By solving all fifty puzzles find the sum of the 3-digit numbers found in the top left corner of each solution grid;
* for example, 483 is the 3-digit number found in the top left corner of the solution grid above.*/ * for example, 483 is the 3-digit number found in the top left corner of the solution grid above.*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <time.h> #include <time.h>
@ -35,266 +37,266 @@ int check(int grid[][9], int i, int j, int n);
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
char dummy[10], dummy_c; char dummy[10], dummy_c;
int i, j, sum = 0, partial; int i, j, sum = 0, partial;
int grid[9][9]; int grid[9][9];
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
FILE *fp; FILE *fp;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
if((fp = fopen("sudoku.txt", "r")) == NULL) if((fp = fopen("sudoku.txt", "r")) == NULL)
{ {
fprintf(stderr, "Error while opening file %s\n", "sudoku.txt"); fprintf(stderr, "Error while opening file %s\n", "sudoku.txt");
return 1; return 1;
} }
while(!feof(fp)) while(!feof(fp))
{ {
fgets(dummy, sizeof(dummy), fp); fgets(dummy, sizeof(dummy), fp);
for(i = 0; i < 9; i++)
{
for(j = 0; j < 9; j++)
{
fscanf(fp, "%c", &dummy_c);
grid[i][j] = (int)dummy_c - '0';
}
for(i = 0; i < 9; i++)
{
for(j = 0; j < 9; j++)
{
fscanf(fp, "%c", &dummy_c); fscanf(fp, "%c", &dummy_c);
grid[i][j] = (int)dummy_c - '0'; }
}
fscanf(fp, "%c", &dummy_c); /* For each sudoku in the file, solve it and sum the number in the
} * top left corner to the total.*/
if(!solve_sudoku(grid))
{
printf("Bad sudoku grid\n");
return 1;
}
/* For each sudoku in the file, solve it and sum the number in the partial = grid[0][0] * 100 + grid[0][1] * 10 + grid[0][2];
* top left corner to the total.*/ sum += partial;
if(!solve_sudoku(grid)) }
{
printf("Bad sudoku grid\n");
return 1;
}
partial = grid[0][0] * 100 + grid[0][1] * 10 + grid[0][2]; fclose(fp);
sum += partial;
}
fclose(fp); clock_gettime(CLOCK_MONOTONIC, &end);
clock_gettime(CLOCK_MONOTONIC, &end); elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; printf("Project Euler, Problem 96\n");
printf("Answer: %d\n", sum);
printf("Project Euler, Problem 96\n"); printf("Elapsed time: %.9lf seconds\n", elapsed);
printf("Answer: %d\n", sum);
printf("Elapsed time: %.9lf seconds\n", elapsed); return 0;
return 0;
} }
int check(int grid[][9], int i, int j, int n) int check(int grid[][9], int i, int j, int n)
{ {
int k, w, ii, jj; int k, w, ii, jj;
for(k = 0; k < 9; k++) for(k = 0; k < 9; k++)
{ {
if(k != j && grid[i][k] == n) if(k != j && grid[i][k] == n)
{ {
return 0;
}
}
for(k = 0; k < 9; k++)
{
if(k != i && grid[k][j] == n)
{
return 0;
}
}
ii = 3 * (i / 3);
jj = 3 * (j / 3);
for(k = 0; k < 3; k++)
{
for(w = 0; w < 3; w++)
{
if(ii + k != i && jj + w != j && grid[ii+k][jj+w] == n)
{
return 0; return 0;
} }
} }
}
return 1; for(k = 0; k < 9; k++)
{
if(k != i && grid[k][j] == n)
{
return 0;
}
}
ii = 3 * (i / 3);
jj = 3 * (j / 3);
for(k = 0; k < 3; k++)
{
for(w = 0; w < 3; w++)
{
if(ii + k != i && jj + w != j && grid[ii+k][jj+w] == n)
{
return 0;
}
}
}
return 1;
} }
int solve_recursive(int grid[][9], int step) int solve_recursive(int grid[][9], int step)
{ {
int i, j, k; int i, j, k;
if(step == 81) if(step == 81)
{ {
return 1; return 1;
} }
i = step / 9; i = step / 9;
j = step % 9; j = step % 9;
if(grid[i][j] != 0) if(grid[i][j] != 0)
{ {
if(solve_recursive(grid, step+1)) if(solve_recursive(grid, step+1))
{ {
return 1; return 1;
} }
} }
else else
{ {
for(k = 1; k <= 9; k++) for(k = 1; k <= 9; k++)
{ {
grid[i][j] = k; grid[i][j] = k;
if(check(grid, i, j, k)) if(check(grid, i, j, k))
{
if(solve_recursive(grid, step+1))
{ {
return 1; if(solve_recursive(grid, step+1))
{
return 1;
}
grid[i][j] = 0;
} }
}
grid[i][j] = 0; grid[i][j] = 0;
} }
}
grid[i][j] = 0; return 0;
}
return 0;
} }
int line_complete(int grid[][9], int i) int line_complete(int grid[][9], int i)
{ {
int n; int n;
for(n = 0; n < 9; n++) for(n = 0; n < 9; n++)
{ {
if(grid[i][n] == 0) if(grid[i][n] == 0)
{ {
return 0; return 0;
} }
} }
return 1; return 1;
} }
int column_complete(int grid[][9], int j) int column_complete(int grid[][9], int j)
{ {
int n; int n;
for(n = 0; n < 9; n++) for(n = 0; n < 9; n++)
{ {
if(grid[n][j] == 0) if(grid[n][j] == 0)
{ {
return 0; return 0;
} }
} }
return 1; return 1;
} }
int solve_sudoku(int grid[][9]) int solve_sudoku(int grid[][9])
{ {
int i, j, k, w, count, val; int i, j, k, w, count, val;
for(w = 0; w < 4; w++) for(w = 0; w < 4; w++)
{ {
for(i = 0; i < 9; i++) for(i = 0; i < 9; i++)
{ {
for(j = 0; j < 9; j++) for(j = 0; j < 9; j++)
{
if(grid[i][j] == 0)
{ {
count = 0; if(grid[i][j] == 0)
{
count = 0;
for(k = 1; k <= 9 && count < 2; k++) for(k = 1; k <= 9 && count < 2; k++)
{ {
grid[i][j] = k; grid[i][j] = k;
if(check(grid, i, j, k) == 1) if(check(grid, i, j, k) == 1)
{ {
count++; count++;
val = k; val = k;
} }
} }
if(count == 1) if(count == 1)
{ {
grid[i][j] = val; grid[i][j] = val;
} }
else else
{ {
grid[i][j] = 0; grid[i][j] = 0;
} }
}
} }
} }
}
for(i = 0; i < 9; i++) for(i = 0; i < 9; i++)
{ {
for(k = 1; k <= 9 && !line_complete(grid, i); k++) for(k = 1; k <= 9 && !line_complete(grid, i); k++)
{
count = 0;
for(j = 0; j < 9 && count < 2; j++)
{ {
if(grid[i][j] == 0) count = 0;
{
grid[i][j] = k;
if(check(grid, i, j, k)) for(j = 0; j < 9 && count < 2; j++)
{ {
count++; if(grid[i][j] == 0)
val = j; {
} grid[i][j] = k;
grid[i][j] = 0; if(check(grid, i, j, k))
} {
count++;
val = j;
}
grid[i][j] = 0;
}
}
if(count == 1)
{
grid[i][val] = k;
}
} }
}
if(count == 1) for(j = 0; j < 9; j++)
{
for(k = 1; k <= 9 && !column_complete(grid, j); k++)
{ {
grid[i][val] = k; count = 0;
for(i = 0; i < 9 && count < 2; i++)
{
if(grid[i][j] == 0)
{
grid[i][j] = k;
if(check(grid, i, j, k))
{
count++;
val = i;
}
grid[i][j] = 0;
}
}
if(count == 1)
{
grid[val][j] = k;
}
} }
} }
} }
for(j = 0; j < 9; j++) return solve_recursive(grid, 0);
{
for(k = 1; k <= 9 && !column_complete(grid, j); k++)
{
count = 0;
for(i = 0; i < 9 && count < 2; i++)
{
if(grid[i][j] == 0)
{
grid[i][j] = k;
if(check(grid, i, j, k))
{
count++;
val = i;
}
grid[i][j] = 0;
}
}
if(count == 1)
{
grid[val][j] = k;
}
}
}
}
return solve_recursive(grid, 0);
} }

View File

@ -5,44 +5,46 @@
* *
* Find the last ten digits of this prime number.*/ * Find the last ten digits of this prime number.*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <time.h> #include <time.h>
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int b = 2, e = 7830457, e_first; int b = 2, e = 7830457, e_first;
long int m = 10000000000, c, result; long int m = 10000000000, c, result;
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
/* Using modular exponentiation algorithm to calculate 2^7830457. The algorithm is: /* Using modular exponentiation algorithm to calculate 2^7830457. The algorithm is:
* Set c=1, e'=0 * Set c=1, e'=0
* Increment e' by 1 * Increment e' by 1
* Set c=b*c%m, where b is the base (2) and m is the modulo (10000000000 since * Set c=b*c%m, where b is the base (2) and m is the modulo (10000000000 since
* we want the last 10 digits. * we want the last 10 digits.
* If e'<e (where e is the exponent), repeat step 3, otherwise c contains the result.*/ * If e'<e (where e is the exponent), repeat step 3, otherwise c contains the result.*/
c = 1; c = 1;
e_first = 0; e_first = 0;
while(e_first < e) while(e_first < e)
{ {
e_first++; e_first++;
c = (b * c) % m; c = (b * c) % m;
} }
result = (c * 28433 + 1) % m; result = (c * 28433 + 1) % m;
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 97\n"); printf("Project Euler, Problem 97\n");
printf("Answer: %ld\n", result); printf("Answer: %ld\n", result);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0; return 0;
} }

View File

@ -8,6 +8,8 @@
* *
* NOTE: The first two lines in the file represent the numbers in the example given above.*/ * NOTE: The first two lines in the file represent the numbers in the example given above.*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <math.h> #include <math.h>
@ -15,46 +17,46 @@
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int i, max_i = -1, base, exp; int i, max_i = -1, base, exp;
double curr, max = 0, elapsed; double curr, max = 0, elapsed;
struct timespec start, end; struct timespec start, end;
FILE *fp; FILE *fp;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
if((fp = fopen("base_exp.txt", "r")) == NULL) if((fp = fopen("base_exp.txt", "r")) == NULL)
{ {
fprintf(stderr, "Error while opening file %s\n", "base_exp.txt"); fprintf(stderr, "Error while opening file %s\n", "base_exp.txt");
return 1; return 1;
} }
for(i = 1; i <= 1000; i++) for(i = 1; i <= 1000; i++)
{ {
fscanf(fp, "%d,%d", &base, &exp); fscanf(fp, "%d,%d", &base, &exp);
/* If /* If
* a^x > b^y * a^x > b^y
* log(a^x) > log(b^y) * log(a^x) > log(b^y)
* x*log(a) > y*log(b). * x*log(a) > y*log(b).
* So for each b^e, calculate e*log(b) and compare these numbers instead.*/ * So for each b^e, calculate e*log(b) and compare these numbers instead.*/
curr = exp * log(base); curr = exp * log(base);
if(curr > max) if(curr > max)
{ {
max = curr; max = curr;
max_i = i; max_i = i;
} }
} }
fclose(fp); fclose(fp);
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 99\n"); printf("Project Euler, Problem 99\n");
printf("Answer: %d\n", max_i); printf("Answer: %d\n", max_i);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0; return 0;
} }

View File

@ -12,6 +12,8 @@
* *
* NOTE: The first two examples in the file represent the triangles in the example given above.*/ * NOTE: The first two examples in the file represent the triangles in the example given above.*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <math.h> #include <math.h>
@ -19,51 +21,51 @@
typedef struct point typedef struct point
{ {
int x; int x;
int y; int y;
}point; } point;
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int count = 0; int count = 0;
FILE *fp; FILE *fp;
point p1, p2, p3; point p1, p2, p3;
double a, b, c, elapsed; double a, b, c, elapsed;
struct timespec start, end; struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
if((fp = fopen("triangles.txt", "r")) == NULL) if((fp = fopen("triangles.txt", "r")) == NULL)
{ {
fprintf(stderr, "Error while opening file %s\n", "triangles.txt"); fprintf(stderr, "Error while opening file %s\n", "triangles.txt");
return 1; return 1;
} }
/* Using the barycentric coordinates method to determine if (0, 0) is inside the triangles.*/ /* Using the barycentric coordinates method to determine if (0, 0) is inside the triangles.*/
while(fscanf(fp, "%d,%d,%d,%d,%d,%d", &p1.x, &p1.y, &p2.x, &p2.y, &p3.x, &p3.y) != EOF) while(fscanf(fp, "%d,%d,%d,%d,%d,%d", &p1.x, &p1.y, &p2.x, &p2.y, &p3.x, &p3.y) != EOF)
{ {
a = (double)((p2.y - p3.y) * (-p3.x) + (p3.x - p2.x) * (-p3.y)) / a = (double)((p2.y - p3.y) * (-p3.x) + (p3.x - p2.x) * (-p3.y)) /
((p2.y - p3.y) * (p1.x - p3.x) + (p3.x - p2.x) * (p1.y - p3.y)); ((p2.y - p3.y) * (p1.x - p3.x) + (p3.x - p2.x) * (p1.y - p3.y));
b = (double)((p3.y - p1.y) * (-p3.x) + (p1.x - p3.x) * (-p3.y)) / b = (double)((p3.y - p1.y) * (-p3.x) + (p1.x - p3.x) * (-p3.y)) /
((p2.y - p3.y) * (p1.x - p3.x) + (p3.x - p2.x) * (p1.y - p3.y)); ((p2.y - p3.y) * (p1.x - p3.x) + (p3.x - p2.x) * (p1.y - p3.y));
c = 1 - a - b; c = 1 - a - b;
if(a >= 0 && a <= 1 && b >= 0 && b <= 1 && c >= 0 && c <= 1) if(a >= 0 && a <= 1 && b >= 0 && b <= 1 && c >= 0 && c <= 1)
{ {
count++; count++;
} }
} }
fclose(fp); fclose(fp);
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 102\n"); printf("Project Euler, Problem 102\n");
printf("Answer: %d\n", count); printf("Answer: %d\n", count);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0; return 0;
} }

152
C/p104.c
View File

@ -7,6 +7,8 @@
* *
* Given that F_k is the first Fibonacci number for which the first nine digits AND the last nine digits are 1-9 pandigital, find k.*/ * Given that F_k is the first Fibonacci number for which the first nine digits AND the last nine digits are 1-9 pandigital, find k.*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <time.h> #include <time.h>
@ -17,101 +19,101 @@ void fib_calc(mpz_t fib, int n);
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
unsigned int i = 2, j, fib1 = 1, fib2 = 1, fibn, fib_int, found = 0; unsigned int i = 2, j, fib1 = 1, fib2 = 1, fibn, fib_int, found = 0;
char *fib_str; char *fib_str;
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
mpz_t fib; mpz_t fib;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
mpz_init(fib); mpz_init(fib);
while(!found) while(!found)
{ {
/* Calculate the next Fibonacci number modulo 10^9 and check if the result is 1-9 pandigital.*/ /* Calculate the next Fibonacci number modulo 10^9 and check if the result is 1-9 pandigital.*/
fibn = (fib1 + fib2) % 1000000000; fibn = (fib1 + fib2) % 1000000000;
fib1 = fib2; fib1 = fib2;
fib2 = fibn; fib2 = fibn;
i++; i++;
/* If the last 9 digits of fib_n are pandigital, calculate the ith Fibonacci number using /* If the last 9 digits of fib_n are pandigital, calculate the ith Fibonacci number using
* the matrix representation.*/ * the matrix representation.*/
if(is_pandigital(fibn, 9)) if(is_pandigital(fibn, 9))
{ {
fib_calc(fib, i); fib_calc(fib, i);
fib_str = mpz_get_str(NULL, 10, fib); fib_str = mpz_get_str(NULL, 10, fib);
fib_int = 0; fib_int = 0;
for(j = 0; j < 9; j++) for(j = 0; j < 9; j++)
{ {
fib_int *= 10; fib_int *= 10;
fib_int += fib_str[j] - '0'; fib_int += fib_str[j] - '0';
} }
if(is_pandigital(fib_int, 9)) if(is_pandigital(fib_int, 9))
{ {
found = 1; found = 1;
} }
free(fib_str); free(fib_str);
} }
} }
mpz_clear(fib); mpz_clear(fib);
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 104\n"); printf("Project Euler, Problem 104\n");
printf("Answer: %d\n", i); printf("Answer: %d\n", i);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0; return 0;
} }
void fib_calc(mpz_t fib, int n) void fib_calc(mpz_t fib, int n)
{ {
int i; int i;
mpz_t tmp, tmp00, tmp01, tmp10, tmp11; mpz_t tmp, tmp00, tmp01, tmp10, tmp11;
mpz_t fib_matrix_base[2][2], fib_matrix[2][2]; mpz_t fib_matrix_base[2][2], fib_matrix[2][2];
mpz_init_set_ui(fib_matrix_base[0][0], 1); mpz_init_set_ui(fib_matrix_base[0][0], 1);
mpz_init_set_ui(fib_matrix_base[0][1], 1); mpz_init_set_ui(fib_matrix_base[0][1], 1);
mpz_init_set_ui(fib_matrix_base[1][0], 1); mpz_init_set_ui(fib_matrix_base[1][0], 1);
mpz_init_set_ui(fib_matrix_base[1][1], 0); mpz_init_set_ui(fib_matrix_base[1][1], 0);
mpz_init_set_ui(fib_matrix[0][0], 1); mpz_init_set_ui(fib_matrix[0][0], 1);
mpz_init_set_ui(fib_matrix[0][1], 1); mpz_init_set_ui(fib_matrix[0][1], 1);
mpz_init_set_ui(fib_matrix[1][0], 1); mpz_init_set_ui(fib_matrix[1][0], 1);
mpz_init_set_ui(fib_matrix[1][1], 0); mpz_init_set_ui(fib_matrix[1][1], 0);
mpz_inits(tmp, tmp00, tmp01, tmp10, tmp11, NULL); mpz_inits(tmp, tmp00, tmp01, tmp10, tmp11, NULL);
for(i = 0; i < n - 1; i++) for(i = 0; i < n - 1; i++)
{ {
mpz_mul(tmp00, fib_matrix[0][0], fib_matrix_base[0][0]); mpz_mul(tmp00, fib_matrix[0][0], fib_matrix_base[0][0]);
mpz_mul(tmp, fib_matrix[0][1], fib_matrix_base[1][0]); mpz_mul(tmp, fib_matrix[0][1], fib_matrix_base[1][0]);
mpz_add(tmp00, tmp00, tmp); mpz_add(tmp00, tmp00, tmp);
mpz_mul(tmp01, fib_matrix[0][0], fib_matrix_base[0][1]); mpz_mul(tmp01, fib_matrix[0][0], fib_matrix_base[0][1]);
mpz_mul(tmp, fib_matrix[0][1], fib_matrix_base[1][1]); mpz_mul(tmp, fib_matrix[0][1], fib_matrix_base[1][1]);
mpz_add(tmp01, tmp01, tmp); mpz_add(tmp01, tmp01, tmp);
mpz_mul(tmp10, fib_matrix[1][0], fib_matrix_base[0][0]); mpz_mul(tmp10, fib_matrix[1][0], fib_matrix_base[0][0]);
mpz_mul(tmp, fib_matrix[1][1], fib_matrix_base[1][0]); mpz_mul(tmp, fib_matrix[1][1], fib_matrix_base[1][0]);
mpz_add(tmp10, tmp10, tmp); mpz_add(tmp10, tmp10, tmp);
mpz_mul(tmp11, fib_matrix[1][0], fib_matrix_base[0][1]); mpz_mul(tmp11, fib_matrix[1][0], fib_matrix_base[0][1]);
mpz_mul(tmp, fib_matrix[1][1], fib_matrix_base[1][1]); mpz_mul(tmp, fib_matrix[1][1], fib_matrix_base[1][1]);
mpz_add(tmp11, tmp11, tmp); mpz_add(tmp11, tmp11, tmp);
mpz_set(fib_matrix[0][0], tmp00); mpz_set(fib_matrix[0][0], tmp00);
mpz_set(fib_matrix[0][1], tmp01); mpz_set(fib_matrix[0][1], tmp01);
mpz_set(fib_matrix[1][0], tmp10); mpz_set(fib_matrix[1][0], tmp10);
mpz_set(fib_matrix[1][1], tmp11); mpz_set(fib_matrix[1][1], tmp11);
} }
mpz_set(fib, fib_matrix[0][1]); mpz_set(fib, fib_matrix[0][1]);
mpz_clears(tmp, tmp00, tmp01, tmp10, tmp11, fib_matrix_base[0][0], mpz_clears(tmp, tmp00, tmp01, tmp10, tmp11, fib_matrix_base[0][0],
fib_matrix_base[0][1], fib_matrix_base[1][0], fib_matrix_base[1][1], fib_matrix_base[0][1], fib_matrix_base[1][0], fib_matrix_base[1][1],
fib_matrix[0][0], fib_matrix[1][0], fib_matrix[1][1], NULL); fib_matrix[0][0], fib_matrix[1][0], fib_matrix[1][1], NULL);
} }

126
C/p112.c
View File

@ -11,6 +11,8 @@
* *
* Find the least number for which the proportion of bouncy numbers is exactly 99%.*/ * Find the least number for which the proportion of bouncy numbers is exactly 99%.*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
@ -20,88 +22,88 @@ int is_bouncy(int n);
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int i = 100, n_bouncy = 0; int i = 100, n_bouncy = 0;
double ratio = 0.0, elapsed; double ratio = 0.0, elapsed;
struct timespec start, end; struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
while(1) while(1)
{ {
if(is_bouncy(i)) if(is_bouncy(i))
{ {
n_bouncy++; n_bouncy++;
} }
ratio = (double)n_bouncy / i; ratio = (double)n_bouncy / i;
if(ratio == 0.99) if(ratio == 0.99)
{ {
break; break;
} }
i++; i++;
} }
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 112\n"); printf("Project Euler, Problem 112\n");
printf("Answer: %d\n", i); printf("Answer: %d\n", i);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0; return 0;
} }
/* Check if the number is bouncy.*/ /* Check if the number is bouncy.*/
int is_bouncy(int n) int is_bouncy(int n)
{ {
int i = 0, l; int i = 0, l;
char n_string[100]; char n_string[100];
sprintf(n_string, "%d", n); sprintf(n_string, "%d", n);
l = strlen(n_string); l = strlen(n_string);
/* Ignore consecutive equal digits.*/ /* Ignore consecutive equal digits.*/
while(i < l - 1 && n_string[i] == n_string[i+1]) while(i < l - 1 && n_string[i] == n_string[i+1])
{ {
i++; i++;
} }
/* If all the digits are the same, the number is not bouncy.*/ /* If all the digits are the same, the number is not bouncy.*/
if(i == l - 1) if(i == l - 1)
{ {
return 0; return 0;
} }
/* If the first two different digits are increasing, if a successive /* If the first two different digits are increasing, if a successive
* digit smaller than the previous digit is found, the number is bouncy.*/ * digit smaller than the previous digit is found, the number is bouncy.*/
if(n_string[i] < n_string[i+1]) if(n_string[i] < n_string[i+1])
{ {
for(; i < l - 1; i++) for(; i < l - 1; i++)
{ {
if(n_string[i] > n_string[i+1]) if(n_string[i] > n_string[i+1])
{ {
return 1; return 1;
} }
} }
} }
/* If the first two different digits are decreasing, if a successive /* If the first two different digits are decreasing, if a successive
* digit larger than the previous digit is found, the number is bouncy.*/ * digit larger than the previous digit is found, the number is bouncy.*/
if(n_string[i] > n_string[i+1]) if(n_string[i] > n_string[i+1])
{ {
for(; i < l - 1; i++) for(; i < l - 1; i++)
{ {
if(n_string[i] < n_string[i+1]) if(n_string[i] < n_string[i+1])
{ {
return 1; return 1;
} }
} }
} }
return 0; return 0;
} }

102
C/p124.c
View File

@ -19,6 +19,8 @@
* *
* If rad(n) is sorted for 1 n 100000, find E(10000).*/ * If rad(n) is sorted for 1 n 100000, find E(10000).*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <math.h> #include <math.h>
@ -29,77 +31,77 @@
typedef struct n_rad typedef struct n_rad
{ {
int n; int n;
int radn; int radn;
}n_radn; } n_radn;
int compare(void *a, void *b); int compare(void *a, void *b);
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int i, *primes; int i, *primes;
n_radn **rads; n_radn **rads;
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
if((primes = sieve(N)) == NULL) if((primes = sieve(N)) == NULL)
{ {
fprintf(stderr, "Error! Sieve function returned NULL\n"); fprintf(stderr, "Error! Sieve function returned NULL\n");
return 1; return 1;
} }
if((rads = (n_radn **)malloc(N*sizeof(n_radn *))) == NULL) if((rads = (n_radn **)malloc(N*sizeof(n_radn *))) == NULL)
{ {
fprintf(stderr, "Error while allocating memory\n"); fprintf(stderr, "Error while allocating memory\n");
return 1; return 1;
} }
for(i = 0; i < N; i++) for(i = 0; i < N; i++)
{ {
if((rads[i] = (n_radn *)malloc(sizeof(n_radn))) == NULL) if((rads[i] = (n_radn *)malloc(sizeof(n_radn))) == NULL)
{ {
fprintf(stderr, "Error while allocating memory\n"); fprintf(stderr, "Error while allocating memory\n");
return 1; return 1;
} }
} }
for(i = 0; i < N; i++) for(i = 0; i < N; i++)
{ {
rads[i]->n = i + 1; rads[i]->n = i + 1;
rads[i]->radn = radical(i+1, primes); rads[i]->radn = radical(i+1, primes);
} }
free(primes); free(primes);
quick_sort((void **)rads, 0, N-1, compare); quick_sort((void **)rads, 0, N-1, compare);
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 124\n"); printf("Project Euler, Problem 124\n");
printf("Answer: %d\n", rads[9999]->n); printf("Answer: %d\n", rads[9999]->n);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0; return 0;
} }
int compare(void *a, void *b) int compare(void *a, void *b)
{ {
n_radn *rad1, *rad2; n_radn *rad1, *rad2;
rad1 = (n_radn *)a; rad1 = (n_radn *)a;
rad2 = (n_radn *)b; rad2 = (n_radn *)b;
if(rad1->radn != rad2->radn) if(rad1->radn != rad2->radn)
{ {
return rad1->radn - rad2->radn; return rad1->radn - rad2->radn;
} }
else else
{ {
return rad1->n - rad2->n; return rad1->n - rad2->n;
} }
} }

View File

@ -6,6 +6,8 @@
* *
* How many reversible numbers are there below one-billion (109)?*/ * How many reversible numbers are there below one-billion (109)?*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <time.h> #include <time.h>
@ -16,58 +18,58 @@ int reverse(int n);
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int i, s, count = 0; int i, s, count = 0;
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
/* Brute force approach, sum each number and their reverse and /* Brute force approach, sum each number and their reverse and
* check if there are only odd digits.*/ * check if there are only odd digits.*/
for(i = 11; i < N; i++) for(i = 11; i < N; i++)
{ {
if(i % 10 != 0) if(i % 10 != 0)
{ {
s = i + reverse(i); s = i + reverse(i);
while(s > 0) while(s > 0)
{
if((s % 10) % 2 == 0)
{ {
break; if((s % 10) % 2 == 0)
{
break;
}
s /= 10;
} }
s /= 10;
}
if(s == 0) if(s == 0)
{ {
count++; count++;
} }
} }
} }
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 145\n"); printf("Project Euler, Problem 145\n");
printf("Answer: %d\n", count); printf("Answer: %d\n", count);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0; return 0;
} }
int reverse(int n) int reverse(int n)
{ {
int reverse = 0; int reverse = 0;
while(n > 0) while(n > 0)
{ {
reverse *= 10; reverse *= 10;
reverse += n % 10; reverse += n % 10;
n /= 10; n /= 10;
} }
return reverse; return reverse;
} }

View File

@ -1,60 +1,62 @@
/* Find the unique positive integer whose square has the form 1_2_3_4_5_6_7_8_9_0, /* Find the unique positive integer whose square has the form 1_2_3_4_5_6_7_8_9_0,
* where each _ is a single digit.*/ * where each _ is a single digit.*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <time.h> #include <time.h>
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int i, found = 0; int i, found = 0;
/* Since the square of n has 19 digits, n must be at least 10^9.*/ /* Since the square of n has 19 digits, n must be at least 10^9.*/
long int n = 1e9, p; long int n = 1e9, p;
double elapsed; double elapsed;
struct timespec start, end; struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start); clock_gettime(CLOCK_MONOTONIC, &start);
while(!found) while(!found)
{ {
/* If the square on n ends with 10, n must be divisible by 10.*/ /* If the square on n ends with 10, n must be divisible by 10.*/
n += 10; n += 10;
p = n * n; p = n * n;
/* A square divisible by 10 is also divisible by 100.*/ /* A square divisible by 10 is also divisible by 100.*/
if(p % 100 != 0) if(p % 100 != 0)
{ {
continue; continue;
} }
/* Check if the digits of the square correspond to the given pattern.*/ /* Check if the digits of the square correspond to the given pattern.*/
i = 9; i = 9;
p /= 100; p /= 100;
while(p > 0) while(p > 0)
{ {
if(p % 10 != i) if(p % 10 != i)
{ {
break; break;
} }
p /= 100; p /= 100;
i--; i--;
} }
if(p == 0) if(p == 0)
{ {
found = 1; found = 1;
} }
} }
clock_gettime(CLOCK_MONOTONIC, &end); clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000;
printf("Project Euler, Problem 206\n"); printf("Project Euler, Problem 206\n");
printf("Answer: %ld\n", n); printf("Answer: %ld\n", n);
printf("Elapsed time: %.9lf seconds\n", elapsed); printf("Elapsed time: %.9lf seconds\n", elapsed);
return 0; return 0;
} }

Some files were not shown because too many files have changed in this diff Show More