diff --git a/C/p001.c b/C/p001.c index c5f33e3..ce2d4d8 100644 --- a/C/p001.c +++ b/C/p001.c @@ -2,36 +2,38 @@ * * Find the sum of all the multiples of 3 or 5 below 1000.*/ +#define _POSIX_C_SOURCE 199309L + #include #include #include int main(int argc, char **argv) { - int i, sum = 0; - double elapsed; - struct timespec start, end; + int i, sum = 0; + double elapsed; + 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, - * check if it's a multiple of 3 or 5, if yes add it to the total.*/ - for(i = 3; i < 1000; i++) - { - if (i % 3 == 0 || i % 5 == 0) - { - sum += i; - } - } + /* 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.*/ + for(i = 3; i < 1000; i++) + { + if (i % 3 == 0 || i % 5 == 0) + { + 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("Answer: %d\n", sum); + printf("Project Euler, Problem 1\n"); + printf("Answer: %d\n", sum); - printf("Elapsed time: %.9lf seconds\n", elapsed); + printf("Elapsed time: %.9lf seconds\n", elapsed); - return 0; + return 0; } diff --git a/C/p002.c b/C/p002.c index 53a293b..1a38528 100644 --- a/C/p002.c +++ b/C/p002.c @@ -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.*/ +#define _POSIX_C_SOURCE 199309L + #include #include #include @@ -12,36 +14,36 @@ int main(int argc, char **argv) { - int fib0 = 1, fib1 = 2, fib2, sum = 2; - double elapsed; - struct timespec start, end; + int fib0 = 1, fib1 = 2, fib2, sum = 2; + double elapsed; + 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 - * sequence smaller than 4 million and if it's even add it to the total.*/ - while(fib2 <= N) - { - if(fib2 % 2 == 0) - { - sum += fib2; - } + /* 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.*/ + while(fib2 <= N) + { + if(fib2 % 2 == 0) + { + sum += fib2; + } - fib0 = fib1; - fib1 = fib2; - fib2 = fib0 + fib1; - } + fib0 = fib1; + fib1 = fib2; + 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("Answer: %d\n", sum); + printf("Project Euler, Problem 2\n"); + printf("Answer: %d\n", sum); - printf("Elapsed time: %.9lf seconds\n", elapsed); + printf("Elapsed time: %.9lf seconds\n", elapsed); - return 0; + return 0; } diff --git a/C/p003.c b/C/p003.c index c5de8da..2882932 100644 --- a/C/p003.c +++ b/C/p003.c @@ -2,6 +2,8 @@ * * What is the largest prime factor of the number 600851475143?*/ +#define _POSIX_C_SOURCE 199309L + #include #include #include @@ -11,26 +13,26 @@ long int max_prime_factor(long int num); int main(int argc, char **argv) { - long int res; - long int num = 600851475143; - double elapsed; - struct timespec start, end; + long int res; + long int num = 600851475143; + double elapsed; + struct timespec start, end; - clock_gettime(CLOCK_MONOTONIC, &start); + clock_gettime(CLOCK_MONOTONIC, &start); - /* Use a function to calculate the largest prime factor.*/ - res = max_prime_factor(num); + /* Use a function to calculate the largest prime factor.*/ + 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("Answer: %ld\n", res); + printf("Project Euler, Problem 3\n"); + 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 @@ -38,39 +40,39 @@ int main(int argc, char **argv) * by its prime factors until only the largest remains.*/ 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.*/ - if(is_prime(num)) - { - return num; - } + /* Use function defined in projecteuler.c to check if a number is prime.*/ + if(is_prime(num)) + { + return num; + } - /* If num is even, find the largest prime factor of num/2.*/ - if(num % 2 == 0) - { - return max_prime_factor(num/2); - } - else - { - i = 3; - - while(1) - { - /* If num is divisible by i and i is prime, find largest prime - * factor of num/i.*/ - if(num % i == 0) - { - if(is_prime(i)) + /* If num is even, find the largest prime factor of num/2.*/ + if(num % 2 == 0) + { + return max_prime_factor(num/2); + } + else + { + i = 3; + + while(1) + { + /* If num is divisible by i and i is prime, find largest prime + * factor of num/i.*/ + if(num % i == 0) { - return max_prime_factor(num/i); + if(is_prime(i)) + { + return max_prime_factor(num/i); + } } - } - i += 2; - } - } + i += 2; + } + } - /* Should never get here.*/ - return -1; + /* Should never get here.*/ + return -1; } diff --git a/C/p004.c b/C/p004.c index 0703fcb..422c6d0 100644 --- a/C/p004.c +++ b/C/p004.c @@ -2,6 +2,8 @@ * * Find the largest palindrome made from the product of two 3-digit numbers.*/ +#define _POSIX_C_SOURCE 199309L + #include #include #include @@ -9,36 +11,36 @@ int main(int argc, char **argv) { - int i, j, max = 0, num; - double elapsed; - struct timespec start, end; + int i, j, max = 0, num; + double elapsed; + 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 - * and check if it's palindrome. If the product found is greater than the - * current maximum, save the current product.*/ - for(i = 999; i >= 100; i--) - { - for(j = i; j >= 100; j--) - { - num = i * j; - /* Use the function defined in projecteuler.c to check if a number is palindrome.*/ - if(num > max && is_palindrome(num, 10)) - { - max = num; - } - } - } + /* 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 + * current maximum, save the current product.*/ + for(i = 999; i >= 100; i--) + { + for(j = i; j >= 100; j--) + { + num = i * j; + /* Use the function defined in projecteuler.c to check if a number is palindrome.*/ + if(num > max && is_palindrome(num, 10)) + { + 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("Answer: %d\n", max); + printf("Project Euler, Problem 4\n"); + printf("Answer: %d\n", max); - printf("Elapsed time: %.9lf seconds\n", elapsed); + printf("Elapsed time: %.9lf seconds\n", elapsed); - return 0; + return 0; } diff --git a/C/p005.c b/C/p005.c index 6d3c63d..d54d8f4 100644 --- a/C/p005.c +++ b/C/p005.c @@ -2,6 +2,8 @@ * * 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 #include #include @@ -9,23 +11,23 @@ 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}; - double elapsed; - struct timespec start, end; + 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; + 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.*/ - res = lcmm(n, 20); + /* Function define in projecteuler.c to find the least common multiple of multiple numbers.*/ + 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("Answer: %ld\n", res); + printf("Project Euler, Problem 5\n"); + printf("Answer: %ld\n", res); - printf("Elapsed time: %.9lf seconds\n", elapsed); + printf("Elapsed time: %.9lf seconds\n", elapsed); - return 0; + return 0; } diff --git a/C/p006.c b/C/p006.c index c38f786..c3ba3ab 100644 --- a/C/p006.c +++ b/C/p006.c @@ -1,44 +1,46 @@ /* The sum of the squares of the first ten natural numbers is, * * 1^2 + 2^2 + ... + 10^2 = 385 - * + * * The square of the sum of the first ten natural numbers is, * * (1 + 2 + ... + 10)^2 = 55^2 = 3025 - * + * * Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640. * * 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 #include #include int main(int argc, char **argv) { - int i, sum_squares = 0, square_sum = 0; - double elapsed; - struct timespec start, end; + int i, sum_squares = 0, square_sum = 0; + double elapsed; + struct timespec start, end; - clock_gettime(CLOCK_MONOTONIC, &start); + clock_gettime(CLOCK_MONOTONIC, &start); - /* Straightforward brute-force approach.*/ - for(i = 1; i <= 100; i++) - { - sum_squares += i*i; - square_sum += i; - } + /* Straightforward brute-force approach.*/ + for(i = 1; i <= 100; i++) + { + sum_squares += i*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("Answer: %d\n", square_sum-sum_squares); + printf("Project Euler, Problem 6\n"); + 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; } diff --git a/C/p007.c b/C/p007.c index 59ece8f..aa90cc7 100644 --- a/C/p007.c +++ b/C/p007.c @@ -2,6 +2,8 @@ * * What is the 10 001st prime number?*/ +#define _POSIX_C_SOURCE 199309L + #include #include #include @@ -9,33 +11,33 @@ int main(int argc, char **argv) { - int count = 1, n = 1, target = 10001; - double elapsed; - struct timespec start, end; + int count = 1, n = 1, target = 10001; + double elapsed; + 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 - * (2 is the only even prime), if it's prime increment count, until the - * target prime is reached.*/ - while(count != target) - { - n += 2; - /* Use the function in projecteuler.c to check if a number is prime.*/ - if(is_prime(n)) - { - count++; - } - } + /* 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 + * target prime is reached.*/ + while(count != target) + { + n += 2; + /* Use the function in projecteuler.c to check if a number is prime.*/ + if(is_prime(n)) + { + 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("Answer: %d\n", n); + printf("Project Euler, Problem 7\n"); + printf("Answer: %d\n", n); - printf("Elapsed time: %.9lf seconds\n", elapsed); + printf("Elapsed time: %.9lf seconds\n", elapsed); - return 0; + return 0; } diff --git a/C/p008.c b/C/p008.c index b324d8a..a50c9aa 100644 --- a/C/p008.c +++ b/C/p008.c @@ -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?*/ +#define _POSIX_C_SOURCE 199309L + #include #include #include int main(int argc, char **argv) { - char string[] = "73167176531330624919225119674426574742355349" - "19493496983520312774506326239578318016984801" - "86947885184385861560789112949495459501737958" - "33195285320880551112540698747158523863050715" - "69329096329522744304355766896648950445244523" - "16173185640309871112172238311362229893423380" - "30813533627661428280644448664523874930358907" - "29629049156044077239071381051585930796086670" - "17242712188399879790879227492190169972088809" - "37766572733300105336788122023542180975125454" - "05947522435258490771167055601360483958644670" - "63244157221553975369781797784617406495514929" - "08625693219784686224828397224137565705605749" - "02614079729686524145351004748216637048440319" - "98900088952434506585412275886668811642717147" - "99244429282308634656748139191231628245861786" - "64583591245665294765456828489128831426076900" - "42242190226710556263211111093705442175069416" - "58960408071984038509624554443629812309878799" - "27244284909188845801561660979191338754992005" - "24063689912560717606058861164671094050775410" - "02256983155200055935729725716362695618826704" - "28252483600823257530420752963450"; - char cur, out; - long int max = 0, tmp = 1; - int i, j; - double elapsed; - struct timespec start, end; + char string[] = "73167176531330624919225119674426574742355349" + "19493496983520312774506326239578318016984801" + "86947885184385861560789112949495459501737958" + "33195285320880551112540698747158523863050715" + "69329096329522744304355766896648950445244523" + "16173185640309871112172238311362229893423380" + "30813533627661428280644448664523874930358907" + "29629049156044077239071381051585930796086670" + "17242712188399879790879227492190169972088809" + "37766572733300105336788122023542180975125454" + "05947522435258490771167055601360483958644670" + "63244157221553975369781797784617406495514929" + "08625693219784686224828397224137565705605749" + "02614079729686524145351004748216637048440319" + "98900088952434506585412275886668811642717147" + "99244429282308634656748139191231628245861786" + "64583591245665294765456828489128831426076900" + "42242190226710556263211111093705442175069416" + "58960408071984038509624554443629812309878799" + "27244284909188845801561660979191338754992005" + "24063689912560717606058861164671094050775410" + "02256983155200055935729725716362695618826704" + "28252483600823257530420752963450"; + char cur, out; + long int max = 0, tmp = 1; + int i, j; + double elapsed; + struct timespec start, end; - clock_gettime(CLOCK_MONOTONIC, &start); + clock_gettime(CLOCK_MONOTONIC, &start); - for(i = 0; i < 1000; i++) - { - /* For the first 13 digits, just multiply them.*/ - 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 - { + for(i = 0; i < 1000; i++) + { + /* For the first 13 digits, just multiply them.*/ + if(i < 13) + { cur = string[i] - '0'; - tmp /= (long int)out; 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("Answer: %ld\n", max); + printf("Project Euler, Problem 8\n"); + printf("Answer: %ld\n", max); - printf("Elapsed time: %.9lf seconds\n", elapsed); + printf("Elapsed time: %.9lf seconds\n", elapsed); - return 0; + return 0; } diff --git a/C/p009.c b/C/p009.c index 9232e3b..692a0b5 100644 --- a/C/p009.c +++ b/C/p009.c @@ -8,6 +8,8 @@ * * Find the product abc.*/ +#define _POSIX_C_SOURCE 199309L + #include #include #include @@ -15,61 +17,61 @@ int main(int argc, char **argv) { - int a, b, c, tmpa, tmpb, tmpc, i, m, n, found = 0; - double elapsed; - struct timespec start, end; + int a, b, c, tmpa, tmpb, tmpc, i, m, n, found = 0; + double elapsed; + struct timespec start, end; - clock_gettime(CLOCK_MONOTONIC, &start); + clock_gettime(CLOCK_MONOTONIC, &start); - /* Brute force approach: generate all the Pythagorean triplets using - * Euclid's formula, until the one where a+b+c=1000 is found.*/ - for(m = 2; found == 0; m++) - { - for(n = 1; n < m && !found; n++) - { - 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) + /* Brute force approach: generate all the Pythagorean triplets using + * Euclid's formula, until the one where a+b+c=1000 is found.*/ + for(m = 2; found == 0; m++) + { + for(n = 1; n < m && !found; n++) + { + if(gcd(m, n) == 1 && ((m % 2 == 0 && n % 2 != 0) || (m % 2 != 0 && n % 2 == 0))) { - found = 1; - break; + a = m * m - n * n; + 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 - { - tmpa = a * i; - tmpb = b * i; - tmpc = c * i; + elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; - if(tmpa + tmpb + tmpc == 1000) - { - a = tmpa; - b = tmpb; - c = tmpc; - found = 1; - break; - } - - i++; - }while(tmpa + tmpb + tmpc < 1000); - } - } - } + printf("Project Euler, Problem 9\n"); + printf("Answer: %d\n", a*b*c); - 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; - - printf("Project Euler, Problem 9\n"); - printf("Answer: %d\n", a*b*c); - - printf("Elapsed time: %.9lf seconds\n", elapsed); - - return 0; + return 0; } diff --git a/C/p010.c b/C/p010.c index bdf0590..836d56b 100644 --- a/C/p010.c +++ b/C/p010.c @@ -2,6 +2,8 @@ * * Find the sum of all the primes below two million.*/ +#define _POSIX_C_SOURCE 199309L + #include #include #include @@ -11,41 +13,41 @@ int main(int argc, char **argv) { - int i; - int *primes; - long int sum = 0; - double elapsed; - struct timespec start, end; + int i; + int *primes; + long int sum = 0; + double elapsed; + struct timespec start, end; - clock_gettime(CLOCK_MONOTONIC, &start); + clock_gettime(CLOCK_MONOTONIC, &start); - /* Use the function in projecteuler.c implementing the - * Sieve of Eratosthenes algorithm to generate primes.*/ - if((primes = sieve(N)) == NULL) - { - fprintf(stderr, "Error! Sieve function returned NULL\n"); - return 1; - } + /* Use the function in projecteuler.c implementing the + * Sieve of Eratosthenes algorithm to generate primes.*/ + if((primes = sieve(N)) == NULL) + { + fprintf(stderr, "Error! Sieve function returned NULL\n"); + return 1; + } - /* Sum all the primes.*/ - for(i = 0; i < N; i++) - { - if(primes[i]) - { - sum += i; - } - } + /* Sum all the primes.*/ + for(i = 0; i < N; i++) + { + if(primes[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("Answer: %ld\n", sum); + printf("Project Euler, Problem 10\n"); + printf("Answer: %ld\n", sum); - printf("Elapsed time: %.9lf seconds\n", elapsed); + printf("Elapsed time: %.9lf seconds\n", elapsed); - return 0; + return 0; } diff --git a/C/p011.c b/C/p011.c index 90a9c9d..a377581 100644 --- a/C/p011.c +++ b/C/p011.c @@ -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?*/ +#define _POSIX_C_SOURCE 199309L + #include #include #include 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}, - {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}, - {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}, - {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}, - {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}, - {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}, - {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}, - {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}, - {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}, - {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}, - {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; - struct timespec start, end; + 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}, + {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}, + {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}, + {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}, + {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}, + {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}, + {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}, + {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}, + {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, 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} + }; + int i, j, k, w, max = 0, prod; + 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 - * adjacent numbers in every direction (horizontal, vertical and the two diagonals). - * If the product is larger than the current maximum, save it.*/ - for(i = 0; i < 17; i++) - { - for(j = 0; j < 17; j++) - { - prod = 1; - /* Horizontal direction.*/ - for(k = j; k < j + 4; k++) - { - prod *= grid[i][k]; - } + /* 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). + * If the product is larger than the current maximum, save it.*/ + for(i = 0; i < 17; i++) + { + for(j = 0; j < 17; j++) + { + prod = 1; + /* Horizontal direction.*/ + for(k = j; k < j + 4; 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) { - max = prod; + max = prod; } - } - } - } - /* 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; - } - } - } + prod = 1; + /* Vertical direction.*/ + for(k = i; k < i + 4; k++) + { + prod *= grid[k][j]; + } + 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"); - printf("Answer: %d\n", max); + 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 11\n"); + printf("Answer: %d\n", max); + + printf("Elapsed time: %.9lf seconds\n", elapsed); + + return 0; } diff --git a/C/p012.c b/C/p012.c index 099952f..25ac7bb 100644 --- a/C/p012.c +++ b/C/p012.c @@ -17,6 +17,8 @@ * * What is the value of the first triangle number to have over five hundred divisors?*/ +#define _POSIX_C_SOURCE 199309L + #include #include #include @@ -24,34 +26,34 @@ int main(int argc, char **argv) { - int i = 0, finished = 0, count, triang = 0; - double elapsed; - struct timespec start, end; + int i = 0, finished = 0, count, triang = 0; + double elapsed; + 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.*/ - while(!finished) - { - i++; - triang += i; - /* Use the function implemented in projecteuler.c to count divisors of a number.*/ - count = count_divisors(triang); - - if(count > 500) - { - finished = 1; - } - } + /* Generate all triangle numbers until the first one with more than 500 divisors is found.*/ + while(!finished) + { + i++; + triang += i; + /* Use the function implemented in projecteuler.c to count divisors of a number.*/ + count = count_divisors(triang); - clock_gettime(CLOCK_MONOTONIC, &end); + if(count > 500) + { + finished = 1; + } + } - elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; + clock_gettime(CLOCK_MONOTONIC, &end); - printf("Project Euler, Problem 12\n"); - printf("Answer: %d\n", triang); + elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; - printf("Elapsed time: %.9lf seconds\n", elapsed); + printf("Project Euler, Problem 12\n"); + printf("Answer: %d\n", triang); - return 0; + printf("Elapsed time: %.9lf seconds\n", elapsed); + + return 0; } diff --git a/C/p013.c b/C/p013.c index fa1cae1..838ec34 100644 --- a/C/p013.c +++ b/C/p013.c @@ -101,6 +101,8 @@ * 20849603980134001723930671666823555245252804609722 * 53503534226472524250874054075591789781264330331690*/ +#define _POSIX_C_SOURCE 199309L + #include #include #include @@ -108,94 +110,95 @@ int main(int argc, char **argv) { - char n[100][51] = {"37107287533902102798797998220837590246510135740250", "46376937677490009712648124896970078050417018260538", - "74324986199524741059474233309513058123726617309629", "91942213363574161572522430563301811072406154908250", - "23067588207539346171171980310421047513778063246676", "89261670696623633820136378418383684178734361726757", - "28112879812849979408065481931592621691275889832738", "44274228917432520321923589422876796487670272189318", - "47451445736001306439091167216856844588711603153276", "70386486105843025439939619828917593665686757934951", - "62176457141856560629502157223196586755079324193331", "64906352462741904929101432445813822663347944758178", - "92575867718337217661963751590579239728245598838407", "58203565325359399008402633568948830189458628227828", - "80181199384826282014278194139940567587151170094390", "35398664372827112653829987240784473053190104293586", - "86515506006295864861532075273371959191420517255829", "71693888707715466499115593487603532921714970056938", - "54370070576826684624621495650076471787294438377604", "53282654108756828443191190634694037855217779295145", - "36123272525000296071075082563815656710885258350721", "45876576172410976447339110607218265236877223636045", - "17423706905851860660448207621209813287860733969412", "81142660418086830619328460811191061556940512689692", - "51934325451728388641918047049293215058642563049483", "62467221648435076201727918039944693004732956340691", - "15732444386908125794514089057706229429197107928209", "55037687525678773091862540744969844508330393682126", - "18336384825330154686196124348767681297534375946515", "80386287592878490201521685554828717201219257766954", - "78182833757993103614740356856449095527097864797581", "16726320100436897842553539920931837441497806860984", - "48403098129077791799088218795327364475675590848030", "87086987551392711854517078544161852424320693150332", - "59959406895756536782107074926966537676326235447210", "69793950679652694742597709739166693763042633987085", - "41052684708299085211399427365734116182760315001271", "65378607361501080857009149939512557028198746004375", - "35829035317434717326932123578154982629742552737307", "94953759765105305946966067683156574377167401875275", - "88902802571733229619176668713819931811048770190271", "25267680276078003013678680992525463401061632866526", - "36270218540497705585629946580636237993140746255962", "24074486908231174977792365466257246923322810917141", - "91430288197103288597806669760892938638285025333403", "34413065578016127815921815005561868836468420090470", - "23053081172816430487623791969842487255036638784583", "11487696932154902810424020138335124462181441773470", - "63783299490636259666498587618221225225512486764533", "67720186971698544312419572409913959008952310058822", - "95548255300263520781532296796249481641953868218774", "76085327132285723110424803456124867697064507995236", - "37774242535411291684276865538926205024910326572967", "23701913275725675285653248258265463092207058596522", - "29798860272258331913126375147341994889534765745501", "18495701454879288984856827726077713721403798879715", - "38298203783031473527721580348144513491373226651381", "34829543829199918180278916522431027392251122869539", - "40957953066405232632538044100059654939159879593635", "29746152185502371307642255121183693803580388584903", - "41698116222072977186158236678424689157993532961922", "62467957194401269043877107275048102390895523597457", - "23189706772547915061505504953922979530901129967519", "86188088225875314529584099251203829009407770775672", - "11306739708304724483816533873502340845647058077308", "82959174767140363198008187129011875491310547126581", - "97623331044818386269515456334926366572897563400500", "42846280183517070527831839425882145521227251250327", - "55121603546981200581762165212827652751691296897789", "32238195734329339946437501907836945765883352399886", - "75506164965184775180738168837861091527357929701337", "62177842752192623401942399639168044983993173312731", - "32924185707147349566916674687634660915035914677504", "99518671430235219628894890102423325116913619626622", - "73267460800591547471830798392868535206946944540724", "76841822524674417161514036427982273348055556214818", - "97142617910342598647204516893989422179826088076852", "87783646182799346313767754307809363333018982642090", - "10848802521674670883215120185883543223812876952786", "71329612474782464538636993009049310363619763878039", - "62184073572399794223406235393808339651327408011116", "66627891981488087797941876876144230030984490851411", - "60661826293682836764744779239180335110989069790714", "85786944089552990653640447425576083659976645795096", - "66024396409905389607120198219976047599490197230297", "64913982680032973156037120041377903785566085089252", - "16730939319872750275468906903707539413042652315011", "94809377245048795150954100921645863754710598436791", - "78639167021187492431995700641917969777599028300699", "15368713711936614952811305876380278410754449733078", - "40789923115535562561142322423255033685442488917353", "44889911501440648020369068063960672322193204149535", - "41503128880339536053299340368006977710650566631954", "81234880673210146739058568557934581403627822703280", - "82616570773948327592232845941706525094512325230608", "22918802058777319719839450180888072429661980811197", - "77158542502016545090413245809786882778948721859617", "72107838435069186155435662884062257473692284509516", - "20849603980134001723930671666823555245252804609722", "53503534226472524250874054075591789781264330331690"}; - char result[100]; - int i; - double elapsed; - struct timespec start, end; - mpz_t a, b; + char n[100][51] = {"37107287533902102798797998220837590246510135740250", "46376937677490009712648124896970078050417018260538", + "74324986199524741059474233309513058123726617309629", "91942213363574161572522430563301811072406154908250", + "23067588207539346171171980310421047513778063246676", "89261670696623633820136378418383684178734361726757", + "28112879812849979408065481931592621691275889832738", "44274228917432520321923589422876796487670272189318", + "47451445736001306439091167216856844588711603153276", "70386486105843025439939619828917593665686757934951", + "62176457141856560629502157223196586755079324193331", "64906352462741904929101432445813822663347944758178", + "92575867718337217661963751590579239728245598838407", "58203565325359399008402633568948830189458628227828", + "80181199384826282014278194139940567587151170094390", "35398664372827112653829987240784473053190104293586", + "86515506006295864861532075273371959191420517255829", "71693888707715466499115593487603532921714970056938", + "54370070576826684624621495650076471787294438377604", "53282654108756828443191190634694037855217779295145", + "36123272525000296071075082563815656710885258350721", "45876576172410976447339110607218265236877223636045", + "17423706905851860660448207621209813287860733969412", "81142660418086830619328460811191061556940512689692", + "51934325451728388641918047049293215058642563049483", "62467221648435076201727918039944693004732956340691", + "15732444386908125794514089057706229429197107928209", "55037687525678773091862540744969844508330393682126", + "18336384825330154686196124348767681297534375946515", "80386287592878490201521685554828717201219257766954", + "78182833757993103614740356856449095527097864797581", "16726320100436897842553539920931837441497806860984", + "48403098129077791799088218795327364475675590848030", "87086987551392711854517078544161852424320693150332", + "59959406895756536782107074926966537676326235447210", "69793950679652694742597709739166693763042633987085", + "41052684708299085211399427365734116182760315001271", "65378607361501080857009149939512557028198746004375", + "35829035317434717326932123578154982629742552737307", "94953759765105305946966067683156574377167401875275", + "88902802571733229619176668713819931811048770190271", "25267680276078003013678680992525463401061632866526", + "36270218540497705585629946580636237993140746255962", "24074486908231174977792365466257246923322810917141", + "91430288197103288597806669760892938638285025333403", "34413065578016127815921815005561868836468420090470", + "23053081172816430487623791969842487255036638784583", "11487696932154902810424020138335124462181441773470", + "63783299490636259666498587618221225225512486764533", "67720186971698544312419572409913959008952310058822", + "95548255300263520781532296796249481641953868218774", "76085327132285723110424803456124867697064507995236", + "37774242535411291684276865538926205024910326572967", "23701913275725675285653248258265463092207058596522", + "29798860272258331913126375147341994889534765745501", "18495701454879288984856827726077713721403798879715", + "38298203783031473527721580348144513491373226651381", "34829543829199918180278916522431027392251122869539", + "40957953066405232632538044100059654939159879593635", "29746152185502371307642255121183693803580388584903", + "41698116222072977186158236678424689157993532961922", "62467957194401269043877107275048102390895523597457", + "23189706772547915061505504953922979530901129967519", "86188088225875314529584099251203829009407770775672", + "11306739708304724483816533873502340845647058077308", "82959174767140363198008187129011875491310547126581", + "97623331044818386269515456334926366572897563400500", "42846280183517070527831839425882145521227251250327", + "55121603546981200581762165212827652751691296897789", "32238195734329339946437501907836945765883352399886", + "75506164965184775180738168837861091527357929701337", "62177842752192623401942399639168044983993173312731", + "32924185707147349566916674687634660915035914677504", "99518671430235219628894890102423325116913619626622", + "73267460800591547471830798392868535206946944540724", "76841822524674417161514036427982273348055556214818", + "97142617910342598647204516893989422179826088076852", "87783646182799346313767754307809363333018982642090", + "10848802521674670883215120185883543223812876952786", "71329612474782464538636993009049310363619763878039", + "62184073572399794223406235393808339651327408011116", "66627891981488087797941876876144230030984490851411", + "60661826293682836764744779239180335110989069790714", "85786944089552990653640447425576083659976645795096", + "66024396409905389607120198219976047599490197230297", "64913982680032973156037120041377903785566085089252", + "16730939319872750275468906903707539413042652315011", "94809377245048795150954100921645863754710598436791", + "78639167021187492431995700641917969777599028300699", "15368713711936614952811305876380278410754449733078", + "40789923115535562561142322423255033685442488917353", "44889911501440648020369068063960672322193204149535", + "41503128880339536053299340368006977710650566631954", "81234880673210146739058568557934581403627822703280", + "82616570773948327592232845941706525094512325230608", "22918802058777319719839450180888072429661980811197", + "77158542502016545090413245809786882778948721859617", "72107838435069186155435662884062257473692284509516", + "20849603980134001723930671666823555245252804609722", "53503534226472524250874054075591789781264330331690" + }; + char result[100]; + int i; + double elapsed; + 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) - * to sum the numbers and get the first 10 digits of the sum.*/ - mpz_inits(a, b, NULL); - mpz_set_str(a, n[0], 10); + /* Using the GNU Multiple Precision Arithmetic Library (GMP) + * to sum the numbers and get the first 10 digits of the sum.*/ + mpz_inits(a, b, NULL); + mpz_set_str(a, n[0], 10); - for(i = 1; i < 100; i++) - { - mpz_set_str(b, n[i], 10); - mpz_add(a, a, b); - } + for(i = 1; i < 100; i++) + { + mpz_set_str(b, n[i], 10); + 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("Answer: "); + printf("Project Euler, Problem 13\n"); + printf("Answer: "); - for(i = 0; i < 10; i++) - { - printf("%c", result[i]); - } + for(i = 0; i < 10; 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; } diff --git a/C/p014.c b/C/p014.c index bfa28b3..c0d2f19 100644 --- a/C/p014.c +++ b/C/p014.c @@ -14,6 +14,8 @@ * * NOTE: Once the chain starts the terms are allowed to go above one million.*/ +#define _POSIX_C_SOURCE 199309L + #include #include #include @@ -26,36 +28,36 @@ int collatz_found[N] = {0}; int main(int argc, char **argv) { - int i, count, max = 0, max_l = 0; - double elapsed; - struct timespec start, end; + int i, count, max = 0, max_l = 0; + double elapsed; + struct timespec start, end; - clock_gettime(CLOCK_MONOTONIC, &start); + clock_gettime(CLOCK_MONOTONIC, &start); - for(i = 1; i < N; i++) - { - /* 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.*/ - count = collatz_length(i); - collatz_found[i] = count; - - if(count > max_l) - { - max_l = count; - max = i; - } - } + for(i = 1; i < N; i++) + { + /* 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.*/ + count = collatz_length(i); + collatz_found[i] = count; - clock_gettime(CLOCK_MONOTONIC, &end); + if(count > max_l) + { + max_l = count; + max = i; + } + } - elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; + clock_gettime(CLOCK_MONOTONIC, &end); - printf("Project Euler, Problem 14\n"); - printf("Answer: %d\n", max); + elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; - printf("Elapsed time: %.9lf seconds\n", elapsed); + printf("Project Euler, Problem 14\n"); + printf("Answer: %d\n", max); - return 0; + printf("Elapsed time: %.9lf seconds\n", elapsed); + + return 0; } /* 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).*/ int collatz_length(long int n) { - if(n == 1) - return 1; + if(n == 1) + return 1; - /* If Collatz(n) has been previously calculated, - * just return the value.*/ - if(n < N && collatz_found[n]) - return collatz_found[n]; + /* If Collatz(n) has been previously calculated, + * just return the value.*/ + if(n < N && collatz_found[n]) + return collatz_found[n]; - if(n % 2 == 0) - return 1 + collatz_length(n/2); - else - return 1 + collatz_length(3*n+1); + if(n % 2 == 0) + return 1 + collatz_length(n/2); + else + return 1 + collatz_length(3*n+1); } diff --git a/C/p015.c b/C/p015.c index 9b62c38..ba6342d 100644 --- a/C/p015.c +++ b/C/p015.c @@ -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 * How many such routes are there through a 20×20 grid?*/ +#define _POSIX_C_SOURCE 199309L + #include #include #include @@ -8,33 +10,33 @@ int main(int argc, char **argv) { - double elapsed; - struct timespec start, end; - mpz_t count, tmp; + double elapsed; + struct timespec start, end; + 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 - * 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. - * This is obtained calculating n!/(k!*(n-k)!), where n=40 and k=20. The GMP - * Library is used to calculate the factorials.*/ - mpz_inits(count, tmp, NULL); - mpz_fac_ui(count, 40); - mpz_fac_ui(tmp, 20); - mpz_mul(tmp, tmp, tmp); - mpz_tdiv_q(count, count, tmp); + /* 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 + * 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 + * Library is used to calculate the factorials.*/ + mpz_inits(count, tmp, NULL); + mpz_fac_ui(count, 40); + mpz_fac_ui(tmp, 20); + mpz_mul(tmp, tmp, 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"); - gmp_printf("Answer: %Zd\n", count); + printf("Project Euler, Problem 15\n"); + 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; } diff --git a/C/p016.c b/C/p016.c index 9940ae4..8752200 100644 --- a/C/p016.c +++ b/C/p016.c @@ -2,6 +2,8 @@ * * What is the sum of the digits of the number 2^1000?*/ +#define _POSIX_C_SOURCE 199309L + #include #include #include @@ -9,37 +11,37 @@ int main(int argc, char **argv) { - double elapsed; - struct timespec start, end; - mpz_t p, sum, r; + double elapsed; + struct timespec start, end; + mpz_t p, sum, r; - clock_gettime(CLOCK_MONOTONIC, &start); + clock_gettime(CLOCK_MONOTONIC, &start); - /* Simply calculate 2^1000 with the GMP Library - * and sum all the digits.*/ - mpz_init_set_ui(p, 2); - mpz_init_set_ui(sum, 0); - mpz_init(r); + /* Simply calculate 2^1000 with the GMP Library + * and sum all the digits.*/ + mpz_init_set_ui(p, 2); + mpz_init_set_ui(sum, 0); + mpz_init(r); - mpz_pow_ui(p, p, 1000); + mpz_pow_ui(p, p, 1000); - while(mpz_cmp_ui(p, 0)) - { - /* To get each digit, simply get the reminder of the division by 10.*/ - mpz_tdiv_qr_ui(p, r, p, 10); - mpz_add(sum, sum, r); - } + while(mpz_cmp_ui(p, 0)) + { + /* To get each digit, simply get the reminder of the division by 10.*/ + mpz_tdiv_qr_ui(p, r, p, 10); + 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"); - gmp_printf("Answer: %Zd\n", sum); + printf("Project Euler, Problem 16\n"); + 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; } diff --git a/C/p017.c b/C/p017.c index f183687..883c99b 100644 --- a/C/p017.c +++ b/C/p017.c @@ -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) * contains 20 letters. The use of "and" when writing out numbers is in compliance with British usage.*/ +#define _POSIX_C_SOURCE 199309L + #include #include #include int main(int argc, char **argv) { - /* 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}; - /* Number of letters for "twenty", "thirty", ..., "ninety".*/ - int n20_90[8] = {6, 6, 5, 5, 5, 7, 6, 6}; - /* Number of letters for "one hundred and", "two hundred and", ..., - * "nine hundred and".*/ - int n100_900[9] = {13, 13, 15, 14, 14, 13, 15, 15, 14}; - /* Number of letters for 1000.*/ - int n1000 = 11; - int sum = 0, i, j; - double elapsed; - struct timespec start, end; + /* 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}; + /* Number of letters for "twenty", "thirty", ..., "ninety".*/ + int n20_90[8] = {6, 6, 5, 5, 5, 7, 6, 6}; + /* Number of letters for "one hundred and", "two hundred and", ..., + * "nine hundred and".*/ + int n100_900[9] = {13, 13, 15, 14, 14, 13, 15, 15, 14}; + /* Number of letters for 1000.*/ + int n1000 = 11; + int sum = 0, i, j; + double elapsed; + struct timespec start, end; - clock_gettime(CLOCK_MONOTONIC, &start); + clock_gettime(CLOCK_MONOTONIC, &start); - /* Sum the letters of the first 19 numbers.*/ - for(i = 0; i < 19; i++) - { - sum += n1_19[i]; - } + /* Sum the letters of the first 19 numbers.*/ + for(i = 0; i < 19; i++) + { + sum += n1_19[i]; + } - /* Add the letters of the numbers from 20 to 99.*/ - for(i = 0; i < 8; i++) - { - /* "Twenty", "thirty", ... "ninety" are used ten times each - * (e.g. "twenty", "twenty one", "twenty two", ..., "twenty nine").*/ - n20_90[i] *= 10; - /* Add "one", "two", ..., "nine".*/ - for(j = 0; j < 9; j++) - { - n20_90[i] += n1_19[j]; - } - sum += n20_90[i]; - } + /* Add the letters of the numbers from 20 to 99.*/ + for(i = 0; i < 8; i++) + { + /* "Twenty", "thirty", ... "ninety" are used ten times each + * (e.g. "twenty", "twenty one", "twenty two", ..., "twenty nine").*/ + n20_90[i] *= 10; + /* Add "one", "two", ..., "nine".*/ + for(j = 0; j < 9; j++) + { + n20_90[i] += n1_19[j]; + } + sum += n20_90[i]; + } - /* Add the letters of the numbers from 100 to 999.*/ - for(i = 0; i < 9; i++) - { - /* "One hundred and", "two hundred and",... are used 100 times each.*/ - n100_900[i] *= 100; - /* Add "one" to "nineteen".*/ - for(j = 0; j < 19; j++) - { - n100_900[i] += n1_19[j]; - } - /* Add "twenty" to "ninety nine", previously calculated.*/ - for(j = 0; j < 8; j++) - { - n100_900[i] += n20_90[j]; - } - /* "One hundred", "two hundred", ... don't have the "and", so remove - * three letters for each of them.*/ - sum += n100_900[i] - 3; - } + /* Add the letters of the numbers from 100 to 999.*/ + for(i = 0; i < 9; i++) + { + /* "One hundred and", "two hundred and",... are used 100 times each.*/ + n100_900[i] *= 100; + /* Add "one" to "nineteen".*/ + for(j = 0; j < 19; j++) + { + n100_900[i] += n1_19[j]; + } + /* Add "twenty" to "ninety nine", previously calculated.*/ + for(j = 0; j < 8; j++) + { + n100_900[i] += n20_90[j]; + } + /* "One hundred", "two hundred", ... don't have the "and", so remove + * three letters for each of them.*/ + sum += n100_900[i] - 3; + } - /* Add "one thousand".*/ - sum += n1000; + /* Add "one thousand".*/ + 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("Answer: %d\n", sum); + printf("Project Euler, Problem 17\n"); + printf("Answer: %d\n", sum); - printf("Elapsed time: %.9lf seconds\n", elapsed); + printf("Elapsed time: %.9lf seconds\n", elapsed); - return 0; + return 0; } diff --git a/C/p018.c b/C/p018.c index 5704467..eedfa4a 100644 --- a/C/p018.c +++ b/C/p018.c @@ -1,5 +1,5 @@ /* By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23. - * + * * 3 * 7 4 * 2 4 6 @@ -25,9 +25,11 @@ * 63 66 04 68 89 53 67 30 73 16 69 87 40 31 * 04 62 98 27 23 09 70 98 73 93 38 53 60 04 23 * - * 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)*/ +#define _POSIX_C_SOURCE 199309L + #include #include #include @@ -35,63 +37,63 @@ int main(int argc, char **argv) { - int i, j, max; - int **triang; - double elapsed; - FILE *fp; - struct timespec start, end; + int i, j, max; + int **triang; + double elapsed; + FILE *fp; + struct timespec start, end; - clock_gettime(CLOCK_MONOTONIC, &start); + clock_gettime(CLOCK_MONOTONIC, &start); - if((triang = (int **)malloc(15*sizeof(int *))) == NULL) - { - fprintf(stderr, "Error while allocating memory\n"); - return 1; - } + if((triang = (int **)malloc(15*sizeof(int *))) == NULL) + { + fprintf(stderr, "Error while allocating memory\n"); + return 1; + } - for(i = 1; i <= 15; i++) - { - if((triang[i-1] = (int *)malloc(i*sizeof(int))) == NULL) - { - fprintf(stderr, "Error while allocating memory\n"); - return 1; - } - } + for(i = 1; i <= 15; i++) + { + if((triang[i-1] = (int *)malloc(i*sizeof(int))) == NULL) + { + fprintf(stderr, "Error while allocating memory\n"); + return 1; + } + } - if((fp = fopen("triang.txt", "r")) == NULL) - { - fprintf(stderr, "Error while opening file %s\n", "triang.txt"); - return 1; - } + if((fp = fopen("triang.txt", "r")) == NULL) + { + fprintf(stderr, "Error while opening file %s\n", "triang.txt"); + return 1; + } - for(i = 1; i <= 15; i++) - { - for(j = 0; j < i; j++) - { - fscanf(fp, "%d", &triang[i-1][j]); - } - } + for(i = 1; i <= 15; i++) + { + for(j = 0; j < i; j++) + { + fscanf(fp, "%d", &triang[i-1][j]); + } + } - fclose(fp); + fclose(fp); - /* Use the function implemented in projecteuler.c to find the maximum path.*/ - max = find_max_path(triang, 15); + /* Use the function implemented in projecteuler.c to find the maximum path.*/ + max = find_max_path(triang, 15); - for(i = 0; i < 15; i++) - { - free(triang[i]); - } + for(i = 0; i < 15; 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("Answer: %d\n", max); + printf("Project Euler, Problem 18\n"); + printf("Answer: %d\n", max); - printf("Elapsed time: %.9lf seconds\n", elapsed); + printf("Elapsed time: %.9lf seconds\n", elapsed); - return 0; + return 0; } diff --git a/C/p019.c b/C/p019.c index 58de517..d8c2e83 100644 --- a/C/p019.c +++ b/C/p019.c @@ -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)?*/ +#define _POSIX_C_SOURCE 199309L + #include #include #include @@ -20,75 +22,75 @@ typedef enum {mon, tue, wed, thu, fri, sat, sun} days; int main(int argc, char **argv) { - int year, i, limit, count = 0; - double elapsed; - struct timespec start, end; - months month; - days day; + int year, i, limit, count = 0; + double elapsed; + struct timespec start, end; + months month; + days day; - clock_gettime(CLOCK_MONOTONIC, &start); + clock_gettime(CLOCK_MONOTONIC, &start); - day = mon; - month = jan; - year = 1900; + day = mon; + month = jan; + year = 1900; - while(year < 2001) - { - /* 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 400.*/ - if(month == feb) - { - if(year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) - { - limit = 29; - } - else - { - limit = 28; - } - } - /* April, June, September and November have 30 days.*/ - else if(month == apr || month == jun || month == sep || month == nov) - { - limit = 30; - } - /* All other months have 31 days.*/ - else - { - limit = 31; - } - /* Loop on every day of the month.*/ - for(i = 1; i <= limit; i++) - { - /* 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 - * 1901 to 2000.*/ - if(year > 1900 && i == 1 && day == sun) - { - count++; - } - /* Change day of the week.*/ - day = (day + 1) % 7; - } - /* At the end of the month, go to next month.*/ - month = (month + 1) % 12; + while(year < 2001) + { + /* 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 400.*/ + if(month == feb) + { + if(year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) + { + limit = 29; + } + else + { + limit = 28; + } + } + /* April, June, September and November have 30 days.*/ + else if(month == apr || month == jun || month == sep || month == nov) + { + limit = 30; + } + /* All other months have 31 days.*/ + else + { + limit = 31; + } + /* Loop on every day of the month.*/ + for(i = 1; i <= limit; i++) + { + /* 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 + * 1901 to 2000.*/ + if(year > 1900 && i == 1 && day == sun) + { + count++; + } + /* Change day of the week.*/ + day = (day + 1) % 7; + } + /* At the end of the month, go to next month.*/ + month = (month + 1) % 12; - /* If we're back to january, increase the year.*/ - if(month == jan) - { - year++; - } - } + /* If we're back to january, increase the year.*/ + if(month == jan) + { + 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("Answer: %d\n", count); + printf("Project Euler, Problem 19\n"); + printf("Answer: %d\n", count); - printf("Elapsed time: %.9lf seconds\n", elapsed); + printf("Elapsed time: %.9lf seconds\n", elapsed); - return 0; + return 0; } diff --git a/C/p020.c b/C/p020.c index 58f198a..0c3865e 100644 --- a/C/p020.c +++ b/C/p020.c @@ -5,6 +5,8 @@ * * Find the sum of the digits in the number 100!*/ +#define _POSIX_C_SOURCE 199309L + #include #include #include @@ -12,35 +14,35 @@ int main(int argc, char **argv) { - double elapsed; - struct timespec start, end; - mpz_t fact, r, sum; + double elapsed; + struct timespec start, end; + 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.*/ - mpz_inits(fact, r, sum, NULL); + /* Calculate the factorial using the GMP Library and sum the digits.*/ + 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)) - { - mpz_tdiv_qr_ui(fact, r, fact, 10); - mpz_add(sum, sum, r); - } + while(mpz_cmp_ui(fact, 0)) + { + mpz_tdiv_qr_ui(fact, r, fact, 10); + 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"); - gmp_printf("Answer: %Zd\n", sum); + printf("Project Euler, Problem 20\n"); + 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; } diff --git a/C/p021.c b/C/p021.c index e39ec2e..62ca24a 100644 --- a/C/p021.c +++ b/C/p021.c @@ -6,6 +6,8 @@ * * Evaluate the sum of all the amicable numbers under 10000.*/ +#define _POSIX_C_SOURCE 199309L + #include #include #include @@ -14,35 +16,35 @@ int main(int argc, char **argv) { - int i, n, sum = 0; - double elapsed; - struct timespec start, end; + int i, n, sum = 0; + double elapsed; + struct timespec start, end; - clock_gettime(CLOCK_MONOTONIC, &start); + clock_gettime(CLOCK_MONOTONIC, &start); - for(i = 2; i < 10000; i++) - { - /* Calculate the sum of proper divisors with the function - * implemented in projecteuler.c.*/ - n = sum_of_divisors(i, 1); - /* If i!=n and the sum of proper divisors of n=i, - * sum the pair of numbers and add it to the total.*/ - if(i != n && sum_of_divisors(n, 1) == i) - { - sum += i + n; - } - } + for(i = 2; i < 10000; i++) + { + /* Calculate the sum of proper divisors with the function + * implemented in projecteuler.c.*/ + n = sum_of_divisors(i, 1); + /* If i!=n and the sum of proper divisors of n=i, + * sum the pair of numbers and add it to the total.*/ + if(i != n && sum_of_divisors(n, 1) == i) + { + 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("Answer: %d\n", sum); + printf("Project Euler, Problem 21\n"); + printf("Answer: %d\n", sum); - printf("Elapsed time: %.9lf seconds\n", elapsed); + printf("Elapsed time: %.9lf seconds\n", elapsed); - return 0; + return 0; } diff --git a/C/p022.c b/C/p022.c index e963be2..c858314 100644 --- a/C/p022.c +++ b/C/p022.c @@ -6,6 +6,8 @@ * * What is the total of all the name scores in the file?*/ +#define _POSIX_C_SOURCE 199309L + #include #include #include @@ -16,86 +18,86 @@ int compare(void *string1, void *string2); int main(int argc, char **argv) { - FILE *fp; - int i, j, n, len, score, sum = 0; - double elapsed; - char *line, **names; - struct timespec start, end; + FILE *fp; + int i, j, n, len, score, sum = 0; + double elapsed; + char *line, **names; + struct timespec start, end; - clock_gettime(CLOCK_MONOTONIC, &start); + clock_gettime(CLOCK_MONOTONIC, &start); - if((fp = fopen("names.txt", "r")) == NULL) - { - fprintf(stderr, "Error while opening file %s\n", "names.txt"); - return 1; - } + if((fp = fopen("names.txt", "r")) == NULL) + { + fprintf(stderr, "Error while opening file %s\n", "names.txt"); + return 1; + } - fscanf(fp, "%ms", &line); + fscanf(fp, "%ms", &line); - fclose(fp); + fclose(fp); - len = strlen(line); - n = 1; + len = strlen(line); + n = 1; - /* Count the names in the file.*/ - for(i = 0; i < len; i++) - { - if(line[i] == ',') - { - n++; - } - } + /* Count the names in the file.*/ + for(i = 0; i < len; i++) + { + if(line[i] == ',') + { + n++; + } + } - if((names = (char **)malloc(n*sizeof(char *))) == NULL) - { - fprintf(stderr, "Error while allocating memory\n"); - return 1; - } + if((names = (char **)malloc(n*sizeof(char *))) == NULL) + { + fprintf(stderr, "Error while allocating memory\n"); + return 1; + } - /* Save each name in a string.*/ - names[0] = strtok(line, ",\""); + /* Save each name in a string.*/ + names[0] = strtok(line, ",\""); - for(i = 1; i < n; i++) - { - names[i] = strtok(NULL, ",\""); - } + for(i = 1; i < n; i++) + { + names[i] = strtok(NULL, ",\""); + } - /* Use quick_sort algorithm implemented in projecteuler.c to sort the names.*/ - quick_sort((void **)names, 0, n-1, compare); + /* Use quick_sort algorithm implemented in projecteuler.c to sort the names.*/ + quick_sort((void **)names, 0, n-1, compare); - /* Calculate the score of each name an multiply by its position.*/ - for(i = 0; i < n; i++) - { - len = strlen(names[i]); - score = 0; - for(j = 0; j < len; j++) - { - score += names[i][j] - 'A' + 1; - } - score *= (i + 1); - sum += score; - } + /* Calculate the score of each name an multiply by its position.*/ + for(i = 0; i < n; i++) + { + len = strlen(names[i]); + score = 0; + for(j = 0; j < len; j++) + { + score += names[i][j] - 'A' + 1; + } + score *= (i + 1); + 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("Answer: %d\n", sum); - printf("Elapsed time: %.9lf seconds\n", elapsed); + printf("Project Euler, Problem 22\n"); + printf("Answer: %d\n", sum); + printf("Elapsed time: %.9lf seconds\n", elapsed); - return 0; + return 0; } /* Function to compare two strings, to pass to the quick_sort function.*/ int compare(void *string1, void *string2) { - char *s1, *s2; + char *s1, *s2; - s1 = (char *)string1; - s2 = (char *)string2; + s1 = (char *)string1; + s2 = (char *)string2; - return strcmp(s1, s2); + return strcmp(s1, s2); } diff --git a/C/p023.c b/C/p023.c index c46d3b4..24c8785 100644 --- a/C/p023.c +++ b/C/p023.c @@ -1,4 +1,4 @@ -/* A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. +/* A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. * For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number. * * A number n is called deficient if the sum of its proper divisors is less than n and it is called abundant if this sum exceeds n. @@ -10,6 +10,8 @@ * * 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 #include #include @@ -20,69 +22,69 @@ int is_abundant(int n); int main(int argc, char **argv) { - int ab_nums[28123], sums[28123] = {0}; - int i, j, sum; - double elapsed; - struct timespec start, end; + int ab_nums[28123], sums[28123] = {0}; + int i, j, sum; + double elapsed; + struct timespec start, end; - clock_gettime(CLOCK_MONOTONIC, &start); + clock_gettime(CLOCK_MONOTONIC, &start); - for(i = 0; i < 28123; i++) - { - /* Find all abundant numbers smaller than 28123.*/ - ab_nums[i] = is_abundant(i+1); - } + for(i = 0; i < 28123; i++) + { + /* Find all abundant numbers smaller than 28123.*/ + ab_nums[i] = is_abundant(i+1); + } - /* For every abundant number, sum every other abundant number greater - * than itself, until the sum exceeds 28123. Record that the resulting - * number is the sum of two abundant numbers.*/ - for(i = 0; i < 28123; i++) - { - if(ab_nums[i]) - { - for(j = i; j < 28123; j++) - { - if(ab_nums[j]) + /* For every abundant number, sum every other abundant number greater + * than itself, until the sum exceeds 28123. Record that the resulting + * number is the sum of two abundant numbers.*/ + for(i = 0; i < 28123; i++) + { + if(ab_nums[i]) + { + for(j = i; j < 28123; j++) { - sum = i + j + 2; + if(ab_nums[j]) + { + sum = i + j + 2; - if(sum <= 28123) - { - sums[sum-1] = 1; - } - else - { - break; - } + if(sum <= 28123) + { + sums[sum-1] = 1; + } + else + { + break; + } + } } - } - } - } + } + } - sum = 0; + sum = 0; - /* Sum every number that was not found as a sum of two abundant numbers.*/ - for(i = 0; i < 28123; i++) - { - if(!sums[i]) - { - sum += i + 1; - } - } + /* Sum every number that was not found as a sum of two abundant numbers.*/ + for(i = 0; i < 28123; i++) + { + if(!sums[i]) + { + 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("Answer: %d\n", sum); + printf("Project Euler, Problem 23\n"); + 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) { - return sum_of_divisors(n, 1) > n; + return sum_of_divisors(n, 1) > n; } diff --git a/C/p024.c b/C/p024.c index 28e2067..eb34095 100644 --- a/C/p024.c +++ b/C/p024.c @@ -5,6 +5,8 @@ * * 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 #include #include @@ -14,69 +16,69 @@ int compare(void *a, void *b); int main(int argc, char **argv) { - int i, res[10]; - int **perm; - double elapsed; - struct timespec start, end; + int i, res[10]; + int **perm; + double elapsed; + struct timespec start, end; - clock_gettime(CLOCK_MONOTONIC, &start); + clock_gettime(CLOCK_MONOTONIC, &start); - if((perm = (int **)malloc(10*sizeof(int *))) == NULL) - { - fprintf(stderr, "Error while allocating memory\n"); - return 1; - } + if((perm = (int **)malloc(10*sizeof(int *))) == NULL) + { + fprintf(stderr, "Error while allocating memory\n"); + return 1; + } - for(i = 0; i < 10; i++) - { - if((perm[i] = (int *)malloc(sizeof(int))) == NULL) - { - fprintf(stderr, "Error while allocating memory\n"); - return 1; - } - *perm[i] = i; - } + for(i = 0; i < 10; i++) + { + if((perm[i] = (int *)malloc(sizeof(int))) == NULL) + { + fprintf(stderr, "Error while allocating memory\n"); + return 1; + } + *perm[i] = i; + } - for(i = 0; i < 999999; i++) - { - /* Function that generates permutations in lexicographic order. - * Finish when the 1000000th is found.*/ - next_permutation((void **)perm, 10, compare); - } + for(i = 0; i < 999999; i++) + { + /* Function that generates permutations in lexicographic order. + * Finish when the 1000000th is found.*/ + next_permutation((void **)perm, 10, compare); + } - for(i = 0; i < 10; i++) - { - res[i] = *perm[i]; - free(perm[i]); - } + for(i = 0; i < 10; i++) + { + res[i] = *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("Answer: "); + printf("Project Euler, Problem 24\n"); + printf("Answer: "); - for(i = 0; i < 10; i++) - { - printf("%d", res[i]); - } + for(i = 0; i < 10; 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 *n1, *n2; + int *n1, *n2; - n1 = (int *)a; - n2 = (int *)b; + n1 = (int *)a; + n2 = (int *)b; - return *n1 - *n2; + return *n1 - *n2; } diff --git a/C/p025.c b/C/p025.c index 9e63c1c..b61defb 100644 --- a/C/p025.c +++ b/C/p025.c @@ -19,6 +19,8 @@ * * What is the index of the first term in the Fibonacci sequence to contain 1000 digits?*/ +#define _POSIX_C_SOURCE 199309L + #include #include #include @@ -27,61 +29,61 @@ int main(int argc, char **argv) { - int i; - double elapsed; - struct timespec start, end; - mpz_t f1, f2, fn; - char *num; - size_t size; + int i; + double elapsed; + struct timespec start, end; + mpz_t f1, f2, fn; + char *num; + size_t size; - clock_gettime(CLOCK_MONOTONIC, &start); + clock_gettime(CLOCK_MONOTONIC, &start); - mpz_init_set_ui(f1, 1); - mpz_init_set_ui(f2, 1); - mpz_init(fn); + mpz_init_set_ui(f1, 1); + mpz_init_set_ui(f2, 1); + mpz_init(fn); - i = 2; + i = 2; - while(1) - { - /* Use the GMP Library to calculate the Fibonacci numbers.*/ - mpz_add(fn, f1, f2); - i++; + while(1) + { + /* Use the GMP Library to calculate the Fibonacci numbers.*/ + mpz_add(fn, f1, f2); + i++; - /* The function mpz_sizeinbase gives the number of digits of - * the number in the given base, but the result is either exact - * or one too big. To check the exact size, the number is - * converted to string and the strlen function is used.*/ - if((size = mpz_sizeinbase(fn, 10)) >= 1000) - { - if((num = (char *)malloc((2+size)*sizeof(char))) == NULL) - { - fprintf(stderr, "Error while allocating memory\n"); - return 1; - } - gmp_sprintf(num, "%Zd", fn); - size = strlen(num); - free(num); - if(size == 1000) - { - break; - } - } + /* The function mpz_sizeinbase gives the number of digits of + * the number in the given base, but the result is either exact + * or one too big. To check the exact size, the number is + * converted to string and the strlen function is used.*/ + if((size = mpz_sizeinbase(fn, 10)) >= 1000) + { + if((num = (char *)malloc((2+size)*sizeof(char))) == NULL) + { + fprintf(stderr, "Error while allocating memory\n"); + return 1; + } + gmp_sprintf(num, "%Zd", fn); + size = strlen(num); + free(num); + if(size == 1000) + { + break; + } + } - mpz_set(f1, f2); - mpz_set(f2, fn); - } + mpz_set(f1, f2); + 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("Answer: %d\n", i); + printf("Project Euler, Problem 25\n"); + printf("Answer: %d\n", i); - printf("Elapsed time: %.9lf seconds\n", elapsed); + printf("Elapsed time: %.9lf seconds\n", elapsed); - return 0; + return 0; } diff --git a/C/p026.c b/C/p026.c index 23754ea..b82c715 100644 --- a/C/p026.c +++ b/C/p026.c @@ -14,6 +14,8 @@ * * 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 #include #include @@ -22,67 +24,67 @@ int main(int argc, char **argv) { - int i, j, n, max = 0, max_n = 0; - double elapsed; - struct timespec start, end; - mpz_t k, div; + int i, j, n, max = 0, max_n = 0; + double elapsed; + struct timespec start, end; + mpz_t k, div; - clock_gettime(CLOCK_MONOTONIC, &start); + clock_gettime(CLOCK_MONOTONIC, &start); - mpz_init(k); - mpz_init(div); + mpz_init(k); + mpz_init(div); - for(i = 2; i < 1000; i++) - { - j = i; + for(i = 2; i < 1000; i++) + { + j = i; - /* 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.*/ - while(j % 2 == 0 && j > 1) - j /= 2; + /* 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.*/ + while(j % 2 == 0 && j > 1) + j /= 2; - while(j % 5 == 0 && j > 1) - j /= 5; + while(j % 5 == 0 && j > 1) + j /= 5; - /* If the denominator had only factors 2 and 5, there is no - * repeating cycle.*/ - if(j == 1) - n = 0; - else - { - n = 1; - mpz_set_ui(k, 9); - mpz_set_ui(div, j); + /* If the denominator had only factors 2 and 5, there is no + * repeating cycle.*/ + if(j == 1) + n = 0; + else + { + n = 1; + mpz_set_ui(k, 9); + mpz_set_ui(div, j); - /* 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 - * 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.*/ - while(!mpz_divisible_p(k, div)) - { - n++; - mpz_mul_ui(k, k, 10); - mpz_add_ui(k, k, 9); - } + /* 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 + * 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.*/ + while(!mpz_divisible_p(k, div)) + { + n++; + mpz_mul_ui(k, k, 10); + mpz_add_ui(k, k, 9); + } - if(n > max) - { - max = n; - max_n = i; - } - } - } + if(n > max) + { + max = n; + 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("Answer: %d\n", max_n); + printf("Project Euler, Problem 26\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; } diff --git a/C/p027.c b/C/p027.c index bc03a5a..aacf743 100644 --- a/C/p027.c +++ b/C/p027.c @@ -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.*/ +#define _POSIX_C_SOURCE 199309L + #include #include #include @@ -25,56 +27,56 @@ int main(int argc, char **argv) { - int a, b, n, p, count, max = 0, save_a, save_b; - double elapsed; - struct timespec start, end; + int a, b, n, p, count, max = 0, save_a, save_b; + double elapsed; + 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.*/ - for(a = -999; a < 1000; a++) - { - for(b = 2; b <= 1000; b++) - { - /* For n=0, n^2+an+b=b, so b must be prime.*/ - if(is_prime(b)) - { - n = 0; - count = 0; - - while(1) + /* Brute force approach, optimized by checking only values of b where b is prime.*/ + for(a = -999; a < 1000; a++) + { + for(b = 2; b <= 1000; b++) + { + /* For n=0, n^2+an+b=b, so b must be prime.*/ + if(is_prime(b)) { - p = n * n + a * n + b; + n = 0; + count = 0; - if(p > 1 && is_prime(p)) - { - count++; - n++; - } - else - { - break; - } + while(1) + { + p = n * n + a * n + b; + + if(p > 1 && is_prime(p)) + { + count++; + n++; + } + else + { + break; + } + } + + if(count > max) + { + max = count; + save_a = a; + save_b = b; + } } + } + } - if(count > max) - { - max = count; - save_a = a; - save_b = b; - } - } - } - } + 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 27\n"); + printf("Answer: %d\n", save_a * save_b); - printf("Project Euler, Problem 27\n"); - printf("Answer: %d\n", save_a * save_b); + printf("Elapsed time: %.9lf seconds\n", elapsed); - printf("Elapsed time: %.9lf seconds\n", elapsed); - - return 0; + return 0; } diff --git a/C/p028.c b/C/p028.c index 7592979..89f0e2e 100644 --- a/C/p028.c +++ b/C/p028.c @@ -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?*/ +#define _POSIX_C_SOURCE 199309L + #include #include #include @@ -18,35 +20,35 @@ int main(int argc, char **argv) { - int i, j, step = 0, limit = N * N, sum = 1; - double elapsed; - struct timespec start, end; + int i, j, step = 0, limit = N * N, sum = 1; + double elapsed; + 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 - * 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, 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) - { - if(i == 0) - { - step += 2; - } + /* 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 + * 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.*/ + for(i = 0, j = 1; j < limit; i = (i + 1) % 4) + { + if(i == 0) + { + step += 2; + } - j += step; - sum += j; - } + j += step; + 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("Answer: %d\n", sum); + printf("Project Euler, Problem 28\n"); + printf("Answer: %d\n", sum); - printf("Elapsed time: %.9lf seconds\n", elapsed); + printf("Elapsed time: %.9lf seconds\n", elapsed); - return 0; + return 0; } diff --git a/C/p029.c b/C/p029.c index 68a321e..a0ab845 100644 --- a/C/p029.c +++ b/C/p029.c @@ -11,6 +11,8 @@ * * 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 #include #include @@ -21,86 +23,86 @@ int compare(void *a, void *b); int main(int argc, char **argv) { - mpz_t a; - mpz_t **powers; - int i, j, count; - double elapsed; - struct timespec start, end; + mpz_t a; + mpz_t **powers; + int i, j, count; + double elapsed; + struct timespec start, end; - clock_gettime(CLOCK_MONOTONIC, &start); + clock_gettime(CLOCK_MONOTONIC, &start); - if((powers = (mpz_t **)malloc(9801*sizeof(mpz_t *))) == NULL) - { - fprintf(stderr, "Error while allocating memory\n"); - return 1; - } + if((powers = (mpz_t **)malloc(9801*sizeof(mpz_t *))) == NULL) + { + fprintf(stderr, "Error while allocating memory\n"); + return 1; + } - for(i = 0; i < 9801; i++) - { - if((powers[i] = (mpz_t *)malloc(sizeof(mpz_t))) == NULL) - { - fprintf(stderr, "Error while allocating memory\n"); - return 1; - } - } + for(i = 0; i < 9801; i++) + { + if((powers[i] = (mpz_t *)malloc(sizeof(mpz_t))) == NULL) + { + fprintf(stderr, "Error while allocating memory\n"); + return 1; + } + } - mpz_init(a); + mpz_init(a); - for(i = 0; i < 9801; i++) - { - mpz_init(*powers[i]); - } + for(i = 0; i < 9801; i++) + { + mpz_init(*powers[i]); + } - /* Using the GMP Library to calculate all the powers.*/ - for(i = 2; i <= 100; i++) - { - mpz_set_ui(a, i); - for(j = 2; j <= 100; j++) - { - mpz_pow_ui(*powers[(i-2)*99+j-2], a, j); - } - } + /* Using the GMP Library to calculate all the powers.*/ + for(i = 2; i <= 100; i++) + { + mpz_set_ui(a, i); + for(j = 2; j <= 100; 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.*/ - quick_sort((void **)powers, 0, 9800, compare); - count = 1; + /* Sort the values and count the different values.*/ + quick_sort((void **)powers, 0, 9800, compare); + count = 1; - for(i = 1; i < 9801; i++) - { - if(mpz_cmp(*powers[i], *powers[i-1])) - { - count++; - } - } + for(i = 1; i < 9801; i++) + { + if(mpz_cmp(*powers[i], *powers[i-1])) + { + count++; + } + } - for(i = 0; i < 9801; i++) - { - mpz_clear(*powers[i]); - free(powers[i]); - } + for(i = 0; i < 9801; i++) + { + mpz_clear(*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("Answer: %d\n", count); + printf("Project Euler, Problem 29\n"); + 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) { - mpz_t *n1, *n2; + mpz_t *n1, *n2; - n1 = (mpz_t *)a; - n2 = (mpz_t *)b; + n1 = (mpz_t *)a; + n2 = (mpz_t *)b; - return mpz_cmp(*n1, *n2); + return mpz_cmp(*n1, *n2); } diff --git a/C/p030.c b/C/p030.c index 0c6f361..7530be6 100644 --- a/C/p030.c +++ b/C/p030.c @@ -10,6 +10,8 @@ * * 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 #include #include @@ -17,41 +19,41 @@ int main(int argc, char **argv) { - int i, j, digit, sum, sum_tot = 0; - double elapsed; - struct timespec start, end; + int i, j, digit, sum, sum_tot = 0; + double elapsed; + struct timespec start, end; - clock_gettime(CLOCK_MONOTONIC, &start); + clock_gettime(CLOCK_MONOTONIC, &start); - /* 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 - * of 5th power of its digits.*/ - for(i = 10; i < 354295; i++) - { - j = i; - sum = 0; + /* 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 + * of 5th power of its digits.*/ + for(i = 10; i < 354295; i++) + { + j = i; + sum = 0; - while(j > 0) - { - digit = j % 10; - sum += (pow(digit, 5)); - j /= 10; - } + while(j > 0) + { + digit = j % 10; + sum += (pow(digit, 5)); + j /= 10; + } - if(sum == i) - { - sum_tot += i; - } - } + if(sum == 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("Answer: %d\n", sum_tot); + printf("Project Euler, problem 30\n"); + printf("Answer: %d\n", sum_tot); - printf("Elapsed time: %.9lf seconds\n", elapsed); + printf("Elapsed time: %.9lf seconds\n", elapsed); - return 0; + return 0; } diff --git a/C/p031.c b/C/p031.c index 2cc77e0..8163596 100644 --- a/C/p031.c +++ b/C/p031.c @@ -8,6 +8,8 @@ * * How many different ways can £2 be made using any number of coins?*/ +#define _POSIX_C_SOURCE 199309L + #include #include #include @@ -18,49 +20,49 @@ int coins[8] = {1, 2, 5, 10, 20, 50, 100, 200}; int main(int argc, char **argv) { - int n; - double elapsed; - struct timespec start, end; + int n; + double elapsed; + 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("Answer: %d\n", n); + printf("Project Euler, Problem 31\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.*/ int count(int value, int n, int i) { - int j; + int j; - for(j = i; j < 8; j++) - { - value += coins[j]; + for(j = i; j < 8; j++) + { + value += coins[j]; - if(value == 200) - { - return n + 1; - } - else if(value > 200) - { - return n; - } - else - { - n = count(value, n, j); - value -= coins[j]; - } - } + if(value == 200) + { + return n + 1; + } + else if(value > 200) + { + return n; + } + else + { + n = count(value, n, j); + value -= coins[j]; + } + } - return n; + return n; } diff --git a/C/p032.c b/C/p032.c index 8bd48a6..e1f7d49 100644 --- a/C/p032.c +++ b/C/p032.c @@ -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.*/ +#define _POSIX_C_SOURCE 199309L + #include #include #include @@ -17,129 +19,129 @@ int compare(void *a, void *b); int main(int argc, char **argv) { - int i, j, p, sum, n = 0, num; - int **products; - char num_s[10]; - double elapsed; - struct timespec start, end; + int i, j, p, sum, n = 0, num; + int **products; + char num_s[10]; + double elapsed; + 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 - * shows that 10 values are sufficient.*/ - if((products = (int **)malloc(10*sizeof(int *))) == NULL) - { - fprintf(stderr, "Error while allocating memory\n"); - return 1; - } + /* Initially I used a bigger array, but printing the resulting products + * shows that 10 values are sufficient.*/ + if((products = (int **)malloc(10*sizeof(int *))) == NULL) + { + fprintf(stderr, "Error while allocating memory\n"); + return 1; + } - for(i = 0; i < 10; i++) - { - if((products[i] = (int *)malloc(sizeof(int))) == NULL) - { - fprintf(stderr, "Error while allocating memory\n"); - return 1; - } - } + for(i = 0; i < 10; i++) + { + if((products[i] = (int *)malloc(sizeof(int))) == NULL) + { + fprintf(stderr, "Error while allocating memory\n"); + return 1; + } + } - /* 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 - * 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 - * 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 - * 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 - * 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 - * the biggest number without repeated digits that multiplied by 2 gives a - * 4 digit number. */ - for(i = 2; i < 9; i++) - { - for(j = 1234; j < 4987; j++) - { - p = i * j; - sprintf(num_s, "%d%d%d", i, j, p); + /* 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 + * 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 + * 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 + * 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 + * 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 + * the biggest number without repeated digits that multiplied by 2 gives a + * 4 digit number. */ + for(i = 2; i < 9; i++) + { + for(j = 1234; j < 4987; j++) + { + p = i * j; + sprintf(num_s, "%d%d%d", i, j, p); - if(strlen(num_s) > 9) - { - break; - } + if(strlen(num_s) > 9) + { + break; + } - num = atoi(num_s); + num = atoi(num_s); - if(is_pandigital(num, 9)) - { - *products[n] = p; - n++; - } - } - } + if(is_pandigital(num, 9)) + { + *products[n] = p; + n++; + } + } + } - /* 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 - * it's the smallest 3-digit number with no digit repetitions and ends at - * 833, because 834*12 has 5 digits.*/ - for(i = 12; i < 99; i++) - { - for(j = 123; j < 834; j++) - { - p = i * j; - sprintf(num_s, "%d%d%d", i, j, p); + /* 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 + * it's the smallest 3-digit number with no digit repetitions and ends at + * 833, because 834*12 has 5 digits.*/ + for(i = 12; i < 99; i++) + { + for(j = 123; j < 834; j++) + { + p = i * j; + sprintf(num_s, "%d%d%d", i, j, p); - if(strlen(num_s) > 9) - { - break; - } + if(strlen(num_s) > 9) + { + break; + } - num = atoi(num_s); + num = atoi(num_s); - if(is_pandigital(num, 9)) - { - *products[n] = p; - n++; - } - } - } - - /* Sort the found products to easily see if there are duplicates.*/ - insertion_sort((void **)products, 0, n-1, compare); + if(is_pandigital(num, 9)) + { + *products[n] = p; + n++; + } + } + } - sum = *products[0]; + /* Sort the found products to easily see if there are duplicates.*/ + insertion_sort((void **)products, 0, n-1, compare); - for(i = 1; i < n; i++) - { - if(*products[i] != *products[i-1]) - { - sum += *products[i]; - } - } + sum = *products[0]; - for(i = 0; i < 10; i++) - { - free(products[i]); - } + for(i = 1; i < n; i++) + { + if(*products[i] != *products[i-1]) + { + sum += *products[i]; + } + } - free(products); + for(i = 0; i < 10; i++) + { + free(products[i]); + } - clock_gettime(CLOCK_MONOTONIC, &end); + free(products); - elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; + clock_gettime(CLOCK_MONOTONIC, &end); - printf("Project Euler, Problem 32\n"); - printf("Answer: %d\n", sum); + elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; - printf("Elapsed time: %.9lf seconds\n", elapsed); + printf("Project Euler, Problem 32\n"); + printf("Answer: %d\n", sum); - return 0; + printf("Elapsed time: %.9lf seconds\n", elapsed); + + return 0; } int compare(void *a, void *b) { - int *n1, *n2; + int *n1, *n2; - n1 = (int *)a; - n2 = (int *)b; + n1 = (int *)a; + n2 = (int *)b; - return *n1 - *n2; + return *n1 - *n2; } diff --git a/C/p033.c b/C/p033.c index 59ed02d..72609c2 100644 --- a/C/p033.c +++ b/C/p033.c @@ -8,6 +8,8 @@ * * 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 #include #include @@ -15,47 +17,47 @@ int main(int argc, char **argv) { - int i, j, n, d, prod_n = 1, prod_d = 1, div; - float f1, f2; - double elapsed; - struct timespec start, end; + int i, j, n, d, prod_n = 1, prod_d = 1, div; + float f1, f2; + double elapsed; + struct timespec start, end; - clock_gettime(CLOCK_MONOTONIC, &start); + clock_gettime(CLOCK_MONOTONIC, &start); - for(i = 11; i < 100; i++) - { - for(j = 11; j < 100; j++) - { - /* If the example is non-trivial, check if cancelling the digit that's equal - * in numerator and denominator gives the same fraction.*/ - 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) + for(i = 11; i < 100; i++) + { + for(j = 11; j < 100; j++) + { + /* If the example is non-trivial, check if cancelling the digit that's equal + * in numerator and denominator gives the same fraction.*/ + if(i % 10 && j % 10 && i != j && i % 10 == j / 10) { - prod_n *= i; - prod_d *= j; + n = i / 10; + 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.*/ - div = gcd(prod_n, prod_d); + /* Find the greater common divisor of the fraction found.*/ + 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("Answer: %d\n", prod_d/div); + printf("Project Euler, Problem 33\n"); + 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; } diff --git a/C/p034.c b/C/p034.c index 047f286..0743963 100644 --- a/C/p034.c +++ b/C/p034.c @@ -4,6 +4,8 @@ * * Note: as 1! = 1 and 2! = 2 are not sums they are not included.*/ +#define _POSIX_C_SOURCE 199309L + #include #include #include @@ -11,66 +13,66 @@ int main(int argc, char **argv) { - int i; - unsigned long int digit; - double elapsed; - struct timespec start, end; - mpz_t a, b, q, sum_f, sum, factorials[10]; + int i; + unsigned long int digit; + double elapsed; + struct timespec start, end; + 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(sum, 0); - mpz_inits(b, q, sum_f, sum, NULL); + mpz_init_set_ui(a, 10); + mpz_init_set_ui(sum, 0); + mpz_inits(b, q, sum_f, sum, NULL); - for(i = 0; i < 10; i++) - { - mpz_init_set_ui(factorials[i], 1); - } + for(i = 0; i < 10; i++) + { + mpz_init_set_ui(factorials[i], 1); + } - /* Pre-calculate factorials of each digit from 0 to 9.*/ - for(i = 2; i < 10; i++) - { - mpz_fac_ui(factorials[i], i); - } + /* Pre-calculate factorials of each digit from 0 to 9.*/ + for(i = 2; i < 10; i++) + { + mpz_fac_ui(factorials[i], i); + } - /* 9!*7<9999999, so 9999999 is certainly un upper bound.*/ - while(mpz_cmp_ui(a, 9999999) < 0) - { - mpz_set(b, a); - mpz_set_ui(sum_f, 0); + /* 9!*7<9999999, so 9999999 is certainly un upper bound.*/ + while(mpz_cmp_ui(a, 9999999) < 0) + { + mpz_set(b, a); + mpz_set_ui(sum_f, 0); - while(mpz_cmp_ui(b, 0)) - { - digit = mpz_fdiv_qr_ui(b, q, b, 10); - mpz_add(sum_f, sum_f, factorials[digit]); - } + while(mpz_cmp_ui(b, 0)) + { + digit = mpz_fdiv_qr_ui(b, q, b, 10); + mpz_add(sum_f, sum_f, factorials[digit]); + } - if(!mpz_cmp(a, sum_f)) - { - mpz_add(sum, sum, a); - } + if(!mpz_cmp(a, sum_f)) + { + 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++) - { - mpz_clear(factorials[i]); - } + for(i = 0; i < 10; 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"); - gmp_printf("Answer: %Zd\n", sum); + printf("Project Euler, Problem 34\n"); + 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; } diff --git a/C/p035.c b/C/p035.c index 0e4156a..1d49c9d 100644 --- a/C/p035.c +++ b/C/p035.c @@ -4,6 +4,8 @@ * * How many circular primes are there below one million?*/ +#define _POSIX_C_SOURCE 199309L + #include #include #include @@ -18,83 +20,83 @@ int *primes; int main(int argc, char **argv) { - int i, count = 13; - double elapsed; - struct timespec start, end; + int i, count = 13; + double elapsed; + 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.*/ - if((primes = sieve(N)) == NULL) - { - fprintf(stderr, "Error! Sieve function returned NULL\n"); - return 1; - } + /* Calculate all primes below one million, then check if they're circular.*/ + if((primes = sieve(N)) == NULL) + { + fprintf(stderr, "Error! Sieve function returned NULL\n"); + return 1; + } - /* Starting from 101 because we already know that there are 13 circular primes below 100.*/ - for(i = 101; i < 1000000; i += 2) - { - if(is_circular_prime(i)) - { - count++; - } - } + /* Starting from 101 because we already know that there are 13 circular primes below 100.*/ + for(i = 101; i < 1000000; i += 2) + { + if(is_circular_prime(i)) + { + 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("Answer: %d\n", count); + printf("Project Euler, Problem 35\n"); + 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 i, tmp, count; + int i, tmp, count; - /* If n is not prime, it's obviously not a circular prime.*/ - if(primes[n] == 0) - { - return 0; - } + /* If n is not prime, it's obviously not a circular prime.*/ + if(primes[n] == 0) + { + return 0; + } - /* The primes below 10 are circular primes.*/ - if(primes[n] == 1 && n < 10) - { - return 1; - } + /* The primes below 10 are circular primes.*/ + if(primes[n] == 1 && n < 10) + { + return 1; + } - tmp = n; - count = 0; + tmp = n; + count = 0; - while(tmp > 0) - { - /* 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.*/ - if(tmp % 2 == 0) - { - return 0; - } - /* Count the number of digits.*/ - count++; - tmp /= 10; - } + while(tmp > 0) + { + /* 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.*/ + if(tmp % 2 == 0) + { + return 0; + } + /* Count the number of digits.*/ + count++; + tmp /= 10; + } - for(i = 1; i < count; i++) - { - /* Generate rotations and check if they're prime.*/ - n = n % (int)pow(10, count-1) * 10 + n / (int)pow(10, count-1); - if(primes[n] == 0) - { - return 0; - } - } + for(i = 1; i < count; i++) + { + /* Generate rotations and check if they're prime.*/ + n = n % (int)pow(10, count-1) * 10 + n / (int)pow(10, count-1); + if(primes[n] == 0) + { + return 0; + } + } - return 1; + return 1; } diff --git a/C/p036.c b/C/p036.c index 35fd9ae..94b09ee 100644 --- a/C/p036.c +++ b/C/p036.c @@ -4,6 +4,8 @@ * * (Please note that the palindromic number, in either base, may not include leading zeros.)*/ +#define _POSIX_C_SOURCE 199309L + #include #include #include @@ -13,31 +15,31 @@ int main(int argc, char **argv) { - int i, sum = 0; - double elapsed; - struct timespec start, end; + int i, sum = 0; + double elapsed; + struct timespec start, end; - clock_gettime(CLOCK_MONOTONIC, &start); + clock_gettime(CLOCK_MONOTONIC, &start); - /* Brute force approach. For every number below 1 million, - * check if they're palindrome in base 2 and 10 using the - * function implemented in projecteuler.c.*/ - for(i = 1; i < N; i += 2) - { - if(is_palindrome(i, 10) && is_palindrome(i, 2)) - { - sum += i; - } - } + /* Brute force approach. For every number below 1 million, + * check if they're palindrome in base 2 and 10 using the + * function implemented in projecteuler.c.*/ + for(i = 1; i < N; i += 2) + { + if(is_palindrome(i, 10) && is_palindrome(i, 2)) + { + 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("Answer: %d\n", sum); + printf("Project Euler, Problem 36\n"); + printf("Answer: %d\n", sum); - printf("Elapsed time: %.9lf seconds\n", elapsed); + printf("Elapsed time: %.9lf seconds\n", elapsed); - return 0; + return 0; } diff --git a/C/p037.c b/C/p037.c index 476cfdd..3129f6a 100644 --- a/C/p037.c +++ b/C/p037.c @@ -5,6 +5,8 @@ * * NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes.*/ +#define _POSIX_C_SOURCE 199309L + #include #include #include @@ -15,75 +17,75 @@ int is_tr_prime(int n); int main(int argc, char **argv) { - int i = 0, n = 1, sum = 0; - double elapsed; - struct timespec start, end; + int i = 0, n = 1, sum = 0; + double elapsed; + struct timespec start, end; - clock_gettime(CLOCK_MONOTONIC, &start); + clock_gettime(CLOCK_MONOTONIC, &start); - /* Check every number until 11 truncatable primes are found.*/ - while(i < 11) - { - if(is_tr_prime(n)) - { - sum += n; - i++; - } - n++; - } + /* Check every number until 11 truncatable primes are found.*/ + while(i < 11) + { + if(is_tr_prime(n)) + { + sum += n; + i++; + } + 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("Answer: %d\n", sum); + printf("Project Euler, Problem 37\n"); + 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 i, tmp; + int i, tmp; - /* One-digit numbers and non-prime numbers are - * not truncatable primes.*/ - if(n < 11 || !is_prime(n)) - { - return 0; - } + /* One-digit numbers and non-prime numbers are + * not truncatable primes.*/ + if(n < 11 || !is_prime(n)) + { + return 0; + } - /* Remove one digit at a time from the right and check - * if the resulting number is prime. Return 0 if it isn't.*/ - tmp = n / 10; + /* Remove one digit at a time from the right and check + * if the resulting number is prime. Return 0 if it isn't.*/ + tmp = n / 10; - while(tmp > 0) - { - if(!is_prime(tmp)) - { - return 0; - } - tmp /= 10; - } + while(tmp > 0) + { + if(!is_prime(tmp)) + { + return 0; + } + tmp /= 10; + } - /* 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 - * is prime. Return 0 when it isn't.*/ - i = 10; - tmp = n % i; + /* 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 + * is prime. Return 0 when it isn't.*/ + i = 10; + tmp = n % i; - while(tmp != n) - { - if(!is_prime(tmp)) - { - return 0; - } - i *= 10; - tmp = n % i; - } + while(tmp != n) + { + if(!is_prime(tmp)) + { + return 0; + } + i *= 10; + tmp = n % i; + } - /* If it gets here, the number is truncatable prime.*/ - return 1; + /* If it gets here, the number is truncatable prime.*/ + return 1; } diff --git a/C/p038.c b/C/p038.c index 917a7a9..1a256c4 100644 --- a/C/p038.c +++ b/C/p038.c @@ -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?*/ +#define _POSIX_C_SOURCE 199309L + #include #include #include @@ -18,64 +20,64 @@ int main(int argc, char **argv) { - int i, j, tmp; - long int n, max = 0; - double elapsed; - struct timespec start, end; + int i, j, tmp; + long int n, max = 0; + double elapsed; + 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 - * 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 - * 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 - * concatenating this two numbers a 10-digit number is obtained.*/ - for(i = 1; i < 10000; i++) - { - n = 0; - j = 1; - do - { - tmp = i * j; - n += tmp; - j++; + /* A brute force approach is used, starting with 1 and multiplying + * 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 + * 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 + * concatenating this two numbers a 10-digit number is obtained.*/ + for(i = 1; i < 10000; i++) + { + n = 0; + j = 1; + do + { + tmp = i * j; + n += tmp; + j++; - if(n > max && is_pandigital(n, 9)) - { - max = n; - } - if(i * j < 10) - { - n *= 10; - } - else if(i * j < 100) - { - n *= 100; - } - else if(i * j < 1000) - { - n *= 1000; - } - else if(i * j < 10000) - { - n *= 10000; - } - else if(i * j < 100000) - { - n *= 100000; - } - }while(n <= 987654321); - } + if(n > max && is_pandigital(n, 9)) + { + max = n; + } + if(i * j < 10) + { + n *= 10; + } + else if(i * j < 100) + { + n *= 100; + } + else if(i * j < 1000) + { + n *= 1000; + } + else if(i * j < 10000) + { + n *= 10000; + } + else if(i * j < 100000) + { + n *= 100000; + } + } 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("Answer: %ld\n", max); + printf("Project Euler, Problem 38\n"); + printf("Answer: %ld\n", max); - printf("Elapsed time: %.9lf seconds\n", elapsed); + printf("Elapsed time: %.9lf seconds\n", elapsed); - return 0; + return 0; } diff --git a/C/p039.c b/C/p039.c index 8ee84d2..61c8469 100644 --- a/C/p039.c +++ b/C/p039.c @@ -4,87 +4,89 @@ * * For which value of p ≤ 1000, is the number of solutions maximised?*/ +#define _POSIX_C_SOURCE 199309L + #include #include #include int main(int argc, char **argv) { - int p, m, n, a, b, c, count, max = 0, res = 0, tmpa, tmpb, tmpc, i; - int savedc[1000] = {0}; - double elapsed; - struct timespec start, end; + int p, m, n, a, b, c, count, max = 0, res = 0, tmpa, tmpb, tmpc, i; + int savedc[1000] = {0}; + double elapsed; + 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.*/ - for(p = 12; p <= 1000; p++) - { - count = 0; - a = 0; - b = 0; - c = 0; + /* Start with p=12 (the smallest pythagorean triplet is (3,4,5) and 3+4+5=12.*/ + for(p = 12; p <= 1000; p++) + { + count = 0; + a = 0; + b = 0; + c = 0; - /* Generate pythagorean triplets.*/ - for(m = 2; m * m < p; m++) - { - 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]) + /* Generate pythagorean triplets.*/ + for(m = 2; m * m < p; m++) + { + for(n = 1; n < m; n++) { - savedc[c] = 1; - count++; + 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; + 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; - tmpa = a; - tmpb = b; - tmpc = c; + /* If the current value is greater than the maximum, + * save the new maximum and the value of p.*/ + if(count > max) + { + max = count; + res = p; + } + } - /* 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; + clock_gettime(CLOCK_MONOTONIC, &end); - /* Increase counter if the new a, b and c give a perimeter=p.*/ - if(tmpa + tmpb + tmpc == p && !savedc[tmpc]) - { - savedc[tmpc] = 1; - count++; - } + elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; - i++; - } - } - } + printf("Project Euler, Problem 39\n"); + printf("Answer: %d\n", res); - /* If the current value is greater than the maximum, - * save the new maximum and the value of p.*/ - if(count > max) - { - max = count; - res = p; - } - } + printf("Elapsed time: %.9lf seconds\n", elapsed); - clock_gettime(CLOCK_MONOTONIC, &end); - - 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; + return 0; } diff --git a/C/p040.c b/C/p040.c index 1183685..48f652e 100644 --- a/C/p040.c +++ b/C/p040.c @@ -8,86 +8,88 @@ * * d_1 × d_10 × d_100 × d_1000 × d_10000 × d_100000 × d_1000000*/ +#define _POSIX_C_SOURCE 199309L + #include #include #include int main(int argc, char **argv) { - int i, value, n; - int digits[1000005]; - double elapsed; - struct timespec start, end; + int i, value, n; + int digits[1000005]; + double elapsed; + struct timespec start, end; - clock_gettime(CLOCK_MONOTONIC, &start); + clock_gettime(CLOCK_MONOTONIC, &start); - i = 1; - value = 1; + i = 1; + value = 1; - /* Loop on all numbers and put the digits in the right place - * in an array. Use modulo and division to get the digits - * for numbers with more than one digit.*/ - while(i <= 1000000) - { - if(value < 10) - { - digits[i-1] = value; - i++; - } - else if(value < 100) - { - digits[i-1] = value / 10; - digits[i] = value % 10; - i += 2; - } - else if(value < 1000) - { - digits[i-1] = value / 100; - digits[i] = (value / 10) % 10; - digits[i+1] = value % 10; - i += 3; - } - else if(value < 10000) - { - digits[i-1] = value / 1000; - digits[i] = (value / 100) % 10; - digits[i+1] = (value / 10) % 10; - digits[i+2] = value % 10; - i += 4; - } - else if(value < 100000) - { - digits[i-1] = value / 10000; - digits[i] = (value / 1000) % 10; - digits[i+1] = (value / 100) % 10; - digits[i+2] = (value / 10) % 10; - digits[i+3] = value % 10; - i += 5; - } - else if(value < 1000000) - { - digits[i-1] = value / 100000; - digits[i] = (value / 10000) % 10; - digits[i+1] = (value / 1000) % 10; - digits[i+2] = (value / 100) % 10; - digits[i+3] = (value / 10) % 10; - digits[i+4] = value % 10; - i += 6; - } - value++; - } + /* Loop on all numbers and put the digits in the right place + * in an array. Use modulo and division to get the digits + * for numbers with more than one digit.*/ + while(i <= 1000000) + { + if(value < 10) + { + digits[i-1] = value; + i++; + } + else if(value < 100) + { + digits[i-1] = value / 10; + digits[i] = value % 10; + i += 2; + } + else if(value < 1000) + { + digits[i-1] = value / 100; + digits[i] = (value / 10) % 10; + digits[i+1] = value % 10; + i += 3; + } + else if(value < 10000) + { + digits[i-1] = value / 1000; + digits[i] = (value / 100) % 10; + digits[i+1] = (value / 10) % 10; + digits[i+2] = value % 10; + i += 4; + } + else if(value < 100000) + { + digits[i-1] = value / 10000; + digits[i] = (value / 1000) % 10; + digits[i+1] = (value / 100) % 10; + digits[i+2] = (value / 10) % 10; + digits[i+3] = value % 10; + i += 5; + } + else if(value < 1000000) + { + digits[i-1] = value / 100000; + digits[i] = (value / 10000) % 10; + digits[i+1] = (value / 1000) % 10; + digits[i+2] = (value / 100) % 10; + digits[i+3] = (value / 10) % 10; + digits[i+4] = value % 10; + i += 6; + } + value++; + } - /* Calculate the product.*/ - n = digits[0] * digits[9] * digits[99] * digits[999] * digits[9999] * digits[99999] * digits[999999]; + /* Calculate the product.*/ + 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("Answer: %d\n", n); + printf("Project Euler, Problem 40\n"); + printf("Answer: %d\n", n); - printf("Elapsed time: %.9lf seconds\n", elapsed); + printf("Elapsed time: %.9lf seconds\n", elapsed); - return 0; + return 0; } diff --git a/C/p041.c b/C/p041.c index 99c98e8..0cb1401 100644 --- a/C/p041.c +++ b/C/p041.c @@ -1,8 +1,10 @@ -/* We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once. For example, 2143 is a 4-digit pandigital +/* We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once. For example, 2143 is a 4-digit pandigital * and is also prime. * * What is the largest n-digit pandigital prime that exists?*/ +#define _POSIX_C_SOURCE 199309L + #include #include #include @@ -13,53 +15,53 @@ int count_digits(int n); int main(int argc, char **argv) { - /* 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 - * also divisible by 3, and therefore the whole number is divisible - * by 3. So we can start from the largest 7-digit pandigital number, - * until we find a prime.*/ - int i = 7654321; - double elapsed; - struct timespec start, end; + /* 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 + * also divisible by 3, and therefore the whole number is divisible + * by 3. So we can start from the largest 7-digit pandigital number, + * until we find a prime.*/ + int i = 7654321; + double elapsed; + struct timespec start, end; - clock_gettime(CLOCK_MONOTONIC, &start); + clock_gettime(CLOCK_MONOTONIC, &start); - while(i > 0) - { - if(is_pandigital(i, count_digits(i)) && is_prime(i)) - { - break; - } - /*Skipping the even numbers.*/ - i -= 2; - } + while(i > 0) + { + if(is_pandigital(i, count_digits(i)) && is_prime(i)) + { + break; + } + /*Skipping the even numbers.*/ + 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("Answer: %d\n", i); + printf("Project Euler, Problem 41\n"); + 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 i = 0; - - if(n == 0) - { - return 1; - } + int i = 0; - while(n > 0) - { - i++; - n /= 10; - } + if(n == 0) + { + return 1; + } - return i; + while(n > 0) + { + i++; + n /= 10; + } + + return i; } diff --git a/C/p042.c b/C/p042.c index a6dfe3d..b2db491 100644 --- a/C/p042.c +++ b/C/p042.c @@ -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, * how many are triangle words?*/ +#define _POSIX_C_SOURCE 199309L + #include #include #include @@ -17,93 +19,93 @@ int is_triang(int n); int main(int argc, char **argv) { - int i, j, n, len, value, count = 0; - char *line, **words; - double elapsed; - FILE *fp; - struct timespec start, end; + int i, j, n, len, value, count = 0; + char *line, **words; + double elapsed; + FILE *fp; + struct timespec start, end; - clock_gettime(CLOCK_MONOTONIC, &start); + clock_gettime(CLOCK_MONOTONIC, &start); - if((fp = fopen("words.txt", "r")) == NULL) - { - fprintf(stderr, "Error while opening file %s\n", "words.txt"); - return 1; - } + if((fp = fopen("words.txt", "r")) == NULL) + { + fprintf(stderr, "Error while opening file %s\n", "words.txt"); + return 1; + } - fscanf(fp, "%ms", &line); + fscanf(fp, "%ms", &line); - fclose(fp); + fclose(fp); - n = 1; - len = strlen(line); + n = 1; + len = strlen(line); - /* Count the words.*/ - for(i = 0; i < len; i++) - { - if(line[i] == ',') - { - n++; - } - } + /* Count the words.*/ + for(i = 0; i < len; i++) + { + if(line[i] == ',') + { + n++; + } + } - if((words = (char **)malloc(n*sizeof(char *))) == NULL) - { - fprintf(stderr, "Error while allocating memory\n"); - return 1; - } + if((words = (char **)malloc(n*sizeof(char *))) == NULL) + { + fprintf(stderr, "Error while allocating memory\n"); + return 1; + } - /* Save the words in an array of strings.*/ - words[0] = strtok(line, ",\""); + /* Save the words in an array of strings.*/ + words[0] = strtok(line, ",\""); - for(i = 1; i < n; i++) - { - words[i] = strtok(NULL, ",\""); - } + for(i = 1; i < n; i++) + { + words[i] = strtok(NULL, ",\""); + } - /* For each word, calculate its value and check if it's a triangle number.*/ - for(i = 0; i < n; i++) - { - value = 0; - len = strlen(words[i]); + /* For each word, calculate its value and check if it's a triangle number.*/ + for(i = 0; i < n; i++) + { + value = 0; + len = strlen(words[i]); - for(j = 0; j < len; j++) - { - value += (words[i][j] - 'A' + 1); - } + for(j = 0; j < len; j++) + { + value += (words[i][j] - 'A' + 1); + } - if(is_triang(value)) - { - count++; - } - } + if(is_triang(value)) + { + count++; + } + } - free(line); - free(words); + free(line); + 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("Answer: %d\n", count); + printf("Project Euler, Problem 42\n"); + 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 i, j; + int i, j; - for(i = 1, j = 1; j <= n; i++, j += i) - { - if(n == j) - { - return 1; - } - } + for(i = 1, j = 1; j <= n; i++, j += i) + { + if(n == j) + { + return 1; + } + } - return 0; + return 0; } diff --git a/C/p043.c b/C/p043.c index 784fcf4..c748ced 100644 --- a/C/p043.c +++ b/C/p043.c @@ -13,6 +13,8 @@ * * Find the sum of all 0 to 9 pandigital numbers with this property.*/ +#define _POSIX_C_SOURCE 199309L + #include #include #include @@ -23,116 +25,116 @@ int has_property(int **n); int main(int argc, char **argv) { - int i; - int **n; - long int sum = 0; - double elapsed; - struct timespec start, end; + int i; + int **n; + long int sum = 0; + double elapsed; + struct timespec start, end; - clock_gettime(CLOCK_MONOTONIC, &start); + clock_gettime(CLOCK_MONOTONIC, &start); - if((n = (int **)malloc(10*sizeof(int *))) == NULL) - { - fprintf(stderr, "Error while allocating memory\n"); - return 1; - } - - for(i = 0; i < 10; i++) - { - if((n[i] = (int *)malloc(sizeof(int))) == NULL) - { - fprintf(stderr, "Error while allocating memory\n"); - return 1; - } - *n[i] = i; - } + if((n = (int **)malloc(10*sizeof(int *))) == NULL) + { + fprintf(stderr, "Error while allocating memory\n"); + return 1; + } - /* Find the next permutation and check if it has the required property. - * Repeat until all the permutations have been found.*/ - while(next_permutation((void **)n, 10, compare) != -1) - { - if(has_property(n)) - { - 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]; - } - } + for(i = 0; i < 10; i++) + { + if((n[i] = (int *)malloc(sizeof(int))) == NULL) + { + fprintf(stderr, "Error while allocating memory\n"); + return 1; + } + *n[i] = i; + } - clock_gettime(CLOCK_MONOTONIC, &end); + /* Find the next permutation and check if it has the required property. + * Repeat until all the permutations have been found.*/ + while(next_permutation((void **)n, 10, compare) != -1) + { + if(has_property(n)) + { + 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]; + } + } - elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; + clock_gettime(CLOCK_MONOTONIC, &end); - printf("Project Euler, Problem 43\n"); - printf("Answer: %ld\n", sum); + elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; - printf("Elapsed time: %.9lf seconds\n", elapsed); + printf("Project Euler, Problem 43\n"); + printf("Answer: %ld\n", sum); - return 0; + printf("Elapsed time: %.9lf seconds\n", elapsed); + + return 0; } int compare(void *a, void *b) { - int *n1, *n2; + int *n1, *n2; - n1 = (int *)a; - n2 = (int *)b; + n1 = (int *)a; + n2 = (int *)b; - return *n1 - *n2; + return *n1 - *n2; } /* Function to check if the value has the desired property.*/ 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) - { - return 0; - } + if(value % 2 != 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) - { - return 0; - } + if(value % 3 != 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) - { - return 0; - } + if(value % 5 != 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) - { - return 0; - } + if(value % 7 != 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) - { - return 0; - } + if(value % 11 != 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) - { - return 0; - } + if(value %13 != 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) - { - return 0; - } + if(value % 17 != 0) + { + return 0; + } - return 1; + return 1; } diff --git a/C/p044.c b/C/p044.c index e781902..423a030 100644 --- a/C/p044.c +++ b/C/p044.c @@ -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; * what is the value of D?*/ +#define _POSIX_C_SOURCE 199309L + #include #include #include @@ -15,42 +17,42 @@ int main(int argc, char **argv) { - int n, m, pn, pm, found = 0; - double elapsed; - struct timespec start, end; + int n, m, pn, pm, found = 0; + double elapsed; + 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 - * is found. Use the function implemented in projecteuler.c to - * check if the sum and difference ot the two numbers is pentagonal.*/ - while(!found) - { - pn = n * (3 * n - 1) / 2; + /* Check all couples of pentagonal numbers until the right one + * is found. Use the function implemented in projecteuler.c to + * check if the sum and difference ot the two numbers is pentagonal.*/ + while(!found) + { + pn = n * (3 * n - 1) / 2; - for(m = 1; m < n; m++) - { - pm = m * (3 * m - 1) / 2; + for(m = 1; m < n; m++) + { + pm = m * (3 * m - 1) / 2; - if(is_pentagonal(pn+pm) && is_pentagonal(pn-pm)) - { - found = 1; - break; - } - } - n++; - } + if(is_pentagonal(pn+pm) && is_pentagonal(pn-pm)) + { + found = 1; + break; + } + } + 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("Answer: %d\n", pn-pm); + printf("Project Euler, Problem 44\n"); + printf("Answer: %d\n", pn-pm); - printf("Elapsed time: %.9lf seconds\n", elapsed); + printf("Elapsed time: %.9lf seconds\n", elapsed); - return 0; + return 0; } diff --git a/C/p045.c b/C/p045.c index e0680d2..d6bb765 100644 --- a/C/p045.c +++ b/C/p045.c @@ -8,6 +8,8 @@ * * Find the next triangle number that is also pentagonal and hexagonal.*/ +#define _POSIX_C_SOURCE 199309L + #include #include #include @@ -16,37 +18,37 @@ int main(int argc, char **argv) { - int found = 0; - long int i, n; - double elapsed; - struct timespec start, end; + int found = 0; + long int i, n; + double elapsed; + struct timespec start, end; - clock_gettime(CLOCK_MONOTONIC, &start); + clock_gettime(CLOCK_MONOTONIC, &start); - i = 143; + i = 143; - while(!found) - { - i++; - /* Hexagonal numbers are also triangle numbers, so it's sufficient - * to generate hexagonal numbers (starting from H_144) and check if - * they're also pentagonal.*/ - n = i * (2 * i - 1); - - if(is_pentagonal(n)) - { - found = 1; - } - } + while(!found) + { + i++; + /* Hexagonal numbers are also triangle numbers, so it's sufficient + * to generate hexagonal numbers (starting from H_144) and check if + * they're also pentagonal.*/ + n = i * (2 * i - 1); - clock_gettime(CLOCK_MONOTONIC, &end); + if(is_pentagonal(n)) + { + found = 1; + } + } - elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; + clock_gettime(CLOCK_MONOTONIC, &end); - printf("Project Euler, Problem 45\n"); - printf("Answer: %ld\n", n); + elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; - printf("Elapsed time: %.9lf seconds\n", elapsed); + printf("Project Euler, Problem 45\n"); + printf("Answer: %ld\n", n); - return 0; + printf("Elapsed time: %.9lf seconds\n", elapsed); + + return 0; } diff --git a/C/p046.c b/C/p046.c index cfd2a5f..2c95562 100644 --- a/C/p046.c +++ b/C/p046.c @@ -11,6 +11,8 @@ * * 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 #include #include @@ -25,73 +27,73 @@ int *primes; int main(int argc, char **argv) { - int i, found = 0; - double elapsed; - struct timespec start, end; + int i, found = 0; + double elapsed; + struct timespec start, end; - clock_gettime(CLOCK_MONOTONIC, &start); + clock_gettime(CLOCK_MONOTONIC, &start); - if((primes = sieve(N)) == NULL) - { - fprintf(stderr, "Error! Sieve function returned NULL\n"); - return 1; - } + if((primes = sieve(N)) == NULL) + { + fprintf(stderr, "Error! Sieve function returned NULL\n"); + return 1; + } - /* For every odd number, check if it's prime, if it is check - * if it satisfies the Goldbach property. Continue until the - * first number that doesn't is found.*/ - for(i = 3; !found && i < N; i += 2) - { - if(!primes[i]) - { - if(!goldbach(i)) - { - found = 1; - } - } - } + /* For every odd number, check if it's prime, if it is check + * if it satisfies the Goldbach property. Continue until the + * first number that doesn't is found.*/ + for(i = 3; !found && i < N; i += 2) + { + if(!primes[i]) + { + if(!goldbach(i)) + { + found = 1; + } + } + } - free(primes); - - clock_gettime(CLOCK_MONOTONIC, &end); + free(primes); - elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; + clock_gettime(CLOCK_MONOTONIC, &end); - printf("Project Euler, Problem 46\n"); - printf("Answer: %d\n", i-2); + elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; - printf("Elapsed time: %.9lf seconds\n", elapsed); + printf("Project Euler, Problem 46\n"); + printf("Answer: %d\n", i-2); - return 0; + printf("Elapsed time: %.9lf seconds\n", elapsed); + + return 0; } int goldbach(int n) { - int i, j, tmp; + int i, j, tmp; - /* Check every prime smaller than n.*/ - for(i = 3; i < n; i += 2) - { - if(primes[i]) - { - j = 1; + /* Check every prime smaller than n.*/ + for(i = 3; i < n; i += 2) + { + if(primes[i]) + { + j = 1; - /* Check if summing twice a square to the prime number - * gives n. Return 1 when succeeding.*/ - do - { - tmp = i + 2 * j * j; - - if(tmp == n) + /* Check if summing twice a square to the prime number + * gives n. Return 1 when succeeding.*/ + do { - return 1; - } + tmp = i + 2 * j * j; - j++; - }while(tmp < n); - } - } + if(tmp == n) + { + return 1; + } - /* Return 0 if no solution is found.*/ - return 0; + j++; + } while(tmp < n); + } + } + + /* Return 0 if no solution is found.*/ + return 0; } diff --git a/C/p047.c b/C/p047.c index 0e383f2..b43a241 100644 --- a/C/p047.c +++ b/C/p047.c @@ -11,6 +11,8 @@ * * 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 #include #include @@ -22,74 +24,74 @@ int *count_factors(int n); int main(int argc, char **argv) { - int i, count, res; - int *factors; - double elapsed; - struct timespec start, end; + int i, count, res; + int *factors; + double elapsed; + struct timespec start, end; - clock_gettime(CLOCK_MONOTONIC, &start); + clock_gettime(CLOCK_MONOTONIC, &start); - if((factors = count_factors(N)) == NULL) - { - fprintf(stderr, "Error! Count_factors function returned NULL\n"); - return 1; - } + if((factors = count_factors(N)) == NULL) + { + fprintf(stderr, "Error! Count_factors function returned NULL\n"); + return 1; + } - count = 0; + count = 0; - for(i = 0; i < N; i++) - { - if(factors[i] == 4) - { - count++; - } - else - { - count = 0; - } + for(i = 0; i < N; i++) + { + if(factors[i] == 4) + { + count++; + } + else + { + count = 0; + } - if(count == 4) - { - res = i - 3; - break; - } - } + if(count == 4) + { + res = i - 3; + 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("Answer: %d\n", res); + printf("Project Euler, Problem 47\n"); + 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 * the distinct prime factors of each number.*/ int *count_factors(int n) { - int i = 2, j; - int *factors; + int i = 2, j; + int *factors; - if((factors = (int *)calloc(n, sizeof(int))) == NULL) - { - return NULL; - } + if((factors = (int *)calloc(n, sizeof(int))) == NULL) + { + return NULL; + } - while(i < n / 2) - { - if(factors[i] == 0) - { - for(j = i; j < n; j += i) - { - factors[j]++; - } - } - i++; - } + while(i < n / 2) + { + if(factors[i] == 0) + { + for(j = i; j < n; j += i) + { + factors[j]++; + } + } + i++; + } - return factors; + return factors; } diff --git a/C/p048.c b/C/p048.c index 774f5ef..5d04aef 100644 --- a/C/p048.c +++ b/C/p048.c @@ -8,38 +8,40 @@ #include #include +#define _POSIX_C_SOURCE 199309L + int main(int argc, char **argv) { - int i; - double elapsed; - struct timespec start, end; - mpz_t power, sum; - char *res; + int i; + double elapsed; + struct timespec start, end; + mpz_t power, sum; + char *res; - clock_gettime(CLOCK_MONOTONIC, &start); + clock_gettime(CLOCK_MONOTONIC, &start); - mpz_init_set_ui(sum, 0); - mpz_init(power); + mpz_init_set_ui(sum, 0); + mpz_init(power); - /* Simply calculate the sum of the powers using the GMP Library.*/ - for(i = 1; i <= 1000; i++) - { - mpz_ui_pow_ui(power, i, i); - mpz_add(sum, sum, power); - } + /* Simply calculate the sum of the powers using the GMP Library.*/ + for(i = 1; i <= 1000; i++) + { + mpz_ui_pow_ui(power, i, i); + mpz_add(sum, sum, power); + } - res = mpz_get_str(NULL, 10, sum); - - mpz_clears(power, sum, NULL); + res = mpz_get_str(NULL, 10, sum); - clock_gettime(CLOCK_MONOTONIC, &end); + mpz_clears(power, sum, NULL); - elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; + clock_gettime(CLOCK_MONOTONIC, &end); - printf("Project Euler, Problem 48\n"); - printf("Answer: %s\n", res+strlen(res)-10); + elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; - printf("Elapsed time: %.9lf seconds\n", elapsed); + printf("Project Euler, Problem 48\n"); + printf("Answer: %s\n", res+strlen(res)-10); - return 0; + printf("Elapsed time: %.9lf seconds\n", elapsed); + + return 0; } diff --git a/C/p049.c b/C/p049.c index 685a28e..816d4da 100644 --- a/C/p049.c +++ b/C/p049.c @@ -6,6 +6,8 @@ * * What 12-digit number do you form by concatenating the three terms in this sequence?*/ +#define _POSIX_C_SOURCE 199309L + #include #include #include @@ -20,86 +22,86 @@ int *primes; int main(int argc, char **argv) { - int i = 1489, j, found = 0; - double elapsed; - struct timespec start, end; + int i = 1489, j, found = 0; + double elapsed; + struct timespec start, end; - clock_gettime(CLOCK_MONOTONIC, &start); + clock_gettime(CLOCK_MONOTONIC, &start); - if((primes = sieve(N)) == NULL) - { - fprintf(stderr, "Error! Sieve function returned NULL\n"); - return 1; - } + if((primes = sieve(N)) == NULL) + { + fprintf(stderr, "Error! Sieve function returned NULL\n"); + return 1; + } - /* 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 - * we need odd numbers because we're looking for primes) up to 4254 (1489+2*4256=10001 which has - * 5 digits.*/ - while(i < N) - { - if(primes[i]) - { - 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)) + /* 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 + * we need odd numbers because we're looking for primes) up to 4254 (1489+2*4256=10001 which has + * 5 digits.*/ + while(i < N) + { + if(primes[i]) + { + for(j = 2; j < 4255; j += 2) { - found = 1; - break; + /* 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; + break; + } } - } - } - if(found) - { - break; - } - i += 2; - } + } + if(found) + { + break; + } + 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("Answer: %d%d%d\n", i, i+j, i+2*j); + printf("Project Euler, Problem 49\n"); + 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 i; - int digits1[10] = {0}, digits2[10] = {0}; + int i; + int digits1[10] = {0}, digits2[10] = {0}; - /* Get digits of a.*/ - while(a > 0) - { - digits1[a%10]++; - a /= 10; - } + /* Get digits of a.*/ + while(a > 0) + { + digits1[a%10]++; + a /= 10; + } - /* Get digits of b.*/ - while(b > 0) - { - digits2[b%10]++; - b /= 10; - } + /* Get digits of b.*/ + while(b > 0) + { + digits2[b%10]++; + b /= 10; + } - /* If they're not the same, return 0.*/ - for(i = 0; i < 10; i++) - { - if(digits1[i] != digits2[i]) - { - return 0; - } - } + /* If they're not the same, return 0.*/ + for(i = 0; i < 10; i++) + { + if(digits1[i] != digits2[i]) + { + return 0; + } + } - return 1; + return 1; } diff --git a/C/p050.c b/C/p050.c index bc061f0..6d70ffa 100644 --- a/C/p050.c +++ b/C/p050.c @@ -8,6 +8,8 @@ * * Which prime, below one-million, can be written as the sum of the most consecutive primes?*/ +#define _POSIX_C_SOURCE 199309L + #include #include #include @@ -18,78 +20,78 @@ int main(int argc, char **argv) { - int i, j, max = 0, max_p = 0, sum, count; - int *primes; - double elapsed; - struct timespec start, end; + int i, j, max = 0, max_p = 0, sum, count; + int *primes; + double elapsed; + struct timespec start, end; - clock_gettime(CLOCK_MONOTONIC, &start); + clock_gettime(CLOCK_MONOTONIC, &start); - if((primes = sieve(N)) == NULL) - { - fprintf(stderr, "Error! Sieve function returned NULL\n"); - return 1; - } + if((primes = sieve(N)) == NULL) + { + fprintf(stderr, "Error! Sieve function returned NULL\n"); + return 1; + } - /* Starting from a prime i, add consecutive primes until the - * 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 - * current maximum. Repeat for all primes below N. - * A separate loop is used for i=2, so later only odd numbers are - * checked for primality.*/ - i = 2; - count = 1; - sum = i; + /* Starting from a prime i, add consecutive primes until the + * 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 + * current maximum. Repeat for all primes below N. + * A separate loop is used for i=2, so later only odd numbers are + * checked for primality.*/ + i = 2; + count = 1; + sum = i; - for(j = i + 1; j < N && sum < N; j++) - { - if(primes[j]) - { - sum += j; - count++; + for(j = i + 1; j < N && sum < N; j++) + { + if(primes[j]) + { + sum += j; + count++; - 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]) + if(sum < N && primes[sum] && count > max) { - sum += j; - count++; - - if(sum < N && primes[sum] && count > max) - { - max = count; - max_p = sum; - } + 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"); - printf("Answer: %d\n", max_p); + free(primes); - 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; } diff --git a/C/p051.c b/C/p051.c index 5115133..0019087 100644 --- a/C/p051.c +++ b/C/p051.c @@ -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 * value family.*/ +#define _POSIX_C_SOURCE 199309L + #include #include #include @@ -23,119 +25,119 @@ int *primes; int main(int argc, char **argv) { - int i; - double elapsed; - struct timespec start, end; + int i; + double elapsed; + 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.*/ - if((primes = sieve(N)) == NULL) - { - fprintf(stderr, "Error! Sieve function returned NULL\n"); - return 1; - } + /* N set to 1000000 as a reasonable limit, which turns out to be enough.*/ + if((primes = sieve(N)) == NULL) + { + fprintf(stderr, "Error! Sieve function returned NULL\n"); + return 1; + } - /* Checking only odd numbers with at least 4 digits.*/ - for(i = 1001; i < N; i += 2) - { - /* 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 - * 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. - * So the smallest number of this family must have three 0s, three 1s or - * three 2s.*/ - if(count_digit(i, 0) >= 3 || count_digit(i, 1) >= 3 || - count_digit(i, 2) >= 3) - { - /* If i is prime, try replacing digits, if obtaining 8 primes, then - * this is the result.*/ - if(primes[i] && replace(i) == 8) - { - break; - } - } - } + /* Checking only odd numbers with at least 4 digits.*/ + for(i = 1001; i < N; i += 2) + { + /* 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 + * 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. + * So the smallest number of this family must have three 0s, three 1s or + * three 2s.*/ + if(count_digit(i, 0) >= 3 || count_digit(i, 1) >= 3 || + count_digit(i, 2) >= 3) + { + /* If i is prime, try replacing digits, if obtaining 8 primes, then + * this is the result.*/ + if(primes[i] && replace(i) == 8) + { + 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("Answer: %d\n", i); + printf("Project Euler, Problem 51\n"); + 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 = 0; + int count = 0; - while(n > 0) - { - if(n % 10 == d) - { - count++; - } - n /= 10; - } + while(n > 0) + { + if(n % 10 == d) + { + count++; + } + n /= 10; + } - return count; + return count; } int replace(int n) { - int i, j, k, w, l, count, max = 0, s_to_n; - char n_to_s[7]; + int i, j, k, w, l, count, max = 0, s_to_n; + char n_to_s[7]; - sprintf(n_to_s, "%d", n); - l = strlen(n_to_s); + sprintf(n_to_s, "%d", n); + l = strlen(n_to_s); - for(i = 0; i < l - 3; i++) - { - for(j = i + 1; j < l - 2; j++) - { - /* 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.*/ - for(k = j + 1; k < l - 1; k++) - { - count = 0; - - for(w = 0; w < 10; w++) + for(i = 0; i < l - 3; i++) + { + for(j = i + 1; j < l - 2; j++) + { + /* 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.*/ + for(k = j + 1; k < l - 1; k++) { - if(i == 0 && w == 0) - { - continue; - } + count = 0; - sprintf(n_to_s, "%d", n); - n_to_s[i] = w + '0'; - n_to_s[j] = w + '0'; - n_to_s[k] = w + '0'; - s_to_n = atoi(n_to_s); + for(w = 0; w < 10; w++) + { + if(i == 0 && w == 0) + { + continue; + } - if(primes[s_to_n]) - { - if(count == 0 && s_to_n != n) - { - continue; - } + sprintf(n_to_s, "%d", n); + n_to_s[i] = w + '0'; + n_to_s[j] = w + '0'; + n_to_s[k] = w + '0'; + 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) - { - max = count; - } - } - } - } - - return max; + return max; } diff --git a/C/p052.c b/C/p052.c index 318ae1b..71f2f51 100644 --- a/C/p052.c +++ b/C/p052.c @@ -2,6 +2,8 @@ * * Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same digits.*/ +#define _POSIX_C_SOURCE 199309L + #include #include #include @@ -10,65 +12,65 @@ int is_permutation(int a, int b); int main(int argc, char **argv) { - int i; - double elapsed; - struct timespec start, end; + int i; + double elapsed; + 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.*/ - while(1) - { - 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)) - { - break; - } + /* Brute force approach, try every integer number until the desired one is found.*/ + while(1) + { + 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)) + { + 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("Answer: %d\n", i); + printf("Project Euler, Problem 52\n"); + 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 i; - int digits1[10] = {0}, digits2[10] = {0}; + int i; + int digits1[10] = {0}, digits2[10] = {0}; - /* Get digits of a.*/ - while(a > 0) - { - digits1[a%10]++; - a /= 10; - } + /* Get digits of a.*/ + while(a > 0) + { + digits1[a%10]++; + a /= 10; + } - /* Get digits of b.*/ - while(b > 0) - { - digits2[b%10]++; - b /= 10; - } + /* Get digits of b.*/ + while(b > 0) + { + digits2[b%10]++; + b /= 10; + } - /* If they're not the same, return 0.*/ - for(i = 0; i < 10; i++) - { - if(digits1[i] != digits2[i]) - { - return 0; - } - } + /* If they're not the same, return 0.*/ + for(i = 0; i < 10; i++) + { + if(digits1[i] != digits2[i]) + { + return 0; + } + } - return 1; + return 1; } diff --git a/C/p053.c b/C/p053.c index b69045a..b3ef2b6 100644 --- a/C/p053.c +++ b/C/p053.c @@ -10,6 +10,8 @@ * * How many, not necessarily distinct, values of (n r) for 1≤n≤100, are greater than one-million?*/ +#define _POSIX_C_SOURCE 199309L + #include #include #include @@ -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 i, j, count = 0; - double elapsed; - struct timespec start, end; - mpz_t bin; - mpz_t factorials[N+1]; + int i, j, count = 0; + double elapsed; + struct timespec start, end; + mpz_t bin; + 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 - * calculate all factorials, then use them for the binomial coefficients.*/ - for(i = 1; i <= N; i++) - { - mpz_init(factorials[i]); - mpz_fac_ui(factorials[i], i); - } + /* Straightforward brute force approach, using the GMP Library. First + * calculate all factorials, then use them for the binomial coefficients.*/ + for(i = 1; i <= N; i++) + { + mpz_init(factorials[i]); + mpz_fac_ui(factorials[i], i); + } - for(i = 23; i <= N; i++) - { - for(j = 1; j <= i; j++) - { - binomial(bin, i, j, factorials); + for(i = 23; i <= N; i++) + { + for(j = 1; j <= i; j++) + { + binomial(bin, i, j, factorials); - if(mpz_cmp_ui(bin, LIMIT) > 0) - count++; - } - } + if(mpz_cmp_ui(bin, LIMIT) > 0) + 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("Answer: %d\n", count); + printf("Project Euler, Problem 53\n"); + 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) { - 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(d1, factorials[k]); - mpz_set(d2, factorials[n-k]); + mpz_set(num, factorials[n]); + mpz_set(d1, factorials[k]); + mpz_set(d2, factorials[n-k]); - mpz_mul(d1, d1, d2); - mpz_tdiv_q(bin, num, d1); + mpz_mul(d1, d1, d2); + mpz_tdiv_q(bin, num, d1); - mpz_clears(num, d1, d2, NULL); + mpz_clears(num, d1, d2, NULL); } diff --git a/C/p054.c b/C/p054.c index e8745d2..f5a28ef 100644 --- a/C/p054.c +++ b/C/p054.c @@ -13,7 +13,7 @@ * The cards are valued in the order: * 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King, Ace. * - * If two players have the same ranked hands then the rank made up of the highest value wins; for example, a pair of eights beats a pair of fives + * If two players have the same ranked hands then the rank made up of the highest value wins; for example, a pair of eights beats a pair of fives * (see example 1 below). But if two ranks tie, for example, both players have a pair of queens, then highest cards in each hand are compared * (see example 4 below); if the highest cards tie then the next highest cards are compared, and so on. * @@ -44,6 +44,8 @@ * * How many hands does Player 1 win?*/ +#define _POSIX_C_SOURCE 199309L + #include #include #include @@ -51,641 +53,641 @@ #include "projecteuler.h" /* Define the values of the cards.*/ -typedef enum{two, three, four, five, six, seven, eight, nine, ten, jack, queen, king, ace} values; +typedef enum {two, three, four, five, six, seven, eight, nine, ten, jack, queen, king, ace} values; /* Define a structure for a card, with value and suit.*/ typedef struct card { - values value; - char suit; -}Card; + values value; + char suit; +} Card; int eval(char *hands); int main(int argc, char **argv) { - int i, count = 0; - double elapsed; - char **hands; - FILE *fp; - struct timespec start, end; + int i, count = 0; + double elapsed; + char **hands; + FILE *fp; + struct timespec start, end; - clock_gettime(CLOCK_MONOTONIC, &start); + clock_gettime(CLOCK_MONOTONIC, &start); - if((fp = fopen("poker.txt", "r")) == NULL) - { - fprintf(stderr, "Error while opening file %s\n", "poker.txt"); - return 1; - } + if((fp = fopen("poker.txt", "r")) == NULL) + { + fprintf(stderr, "Error while opening file %s\n", "poker.txt"); + return 1; + } - if((hands = (char **)malloc(1000*sizeof(char *))) == NULL) - { - fprintf(stderr, "Error while allocating memory\n"); - return 1; - } + if((hands = (char **)malloc(1000*sizeof(char *))) == NULL) + { + fprintf(stderr, "Error while allocating memory\n"); + return 1; + } - for(i=0; i<1000; i++) - { - if((hands[i] = (char *)malloc(31*sizeof(char))) == NULL) - { - fprintf(stderr, "Error while allocating memory\n"); - return 1; - } - } + for(i=0; i<1000; i++) + { + if((hands[i] = (char *)malloc(31*sizeof(char))) == NULL) + { + fprintf(stderr, "Error while allocating memory\n"); + return 1; + } + } - for(i = 0; i < 1000; i++) - { - fgets(hands[i], 31*sizeof(char), fp); + for(i = 0; i < 1000; i++) + { + fgets(hands[i], 31*sizeof(char), fp); - /* Count how many hands player 1 wins, using an evaluation function.*/ - if(eval(hands[i]) > 0) - { - count++; - } - free(hands[i]); - } + /* Count how many hands player 1 wins, using an evaluation function.*/ + if(eval(hands[i]) > 0) + { + count++; + } + free(hands[i]); + } - fclose(fp); - free(hands); + fclose(fp); + free(hands); - 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 54\n"); - printf("Answer: %d\n", count); + printf("Project Euler, Problem 54\n"); + 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 *card1, void *card2) { - Card *c1, *c2; + Card *c1, *c2; - c1 = (Card *)card1; - c2 = (Card *)card2; + c1 = (Card *)card1; + c2 = (Card *)card2; - return c1->value - c2->value; + return c1->value - c2->value; } void get_value(Card *card, char value) { - if(value == '2') - { - card->value = two; - } - else if(value == '3') - { - card->value = three; - } - else if(value == '4') - { - card->value = four; - } - else if(value == '5') - { - card->value = five; - } - else if(value == '6') - { - card->value = six; - } - else if(value == '7') - { - card->value = seven; - } - else if(value == '8') - { - card->value = eight; - } - else if(value == '9') - { - card->value = nine; - } - else if(value == 'T') - { - card->value = ten; - } - else if(value == 'J') - { - card->value = jack; - } - else if(value == 'Q') - { - card->value = queen; - } - else if(value == 'K') - { - card->value = king; - } - else if(value == 'A') - { - card->value = ace; - } + if(value == '2') + { + card->value = two; + } + else if(value == '3') + { + card->value = three; + } + else if(value == '4') + { + card->value = four; + } + else if(value == '5') + { + card->value = five; + } + else if(value == '6') + { + card->value = six; + } + else if(value == '7') + { + card->value = seven; + } + else if(value == '8') + { + card->value = eight; + } + else if(value == '9') + { + card->value = nine; + } + else if(value == 'T') + { + card->value = ten; + } + else if(value == 'J') + { + card->value = jack; + } + else if(value == 'Q') + { + card->value = queen; + } + else if(value == 'K') + { + card->value = king; + } + else if(value == 'A') + { + card->value = ace; + } } int eval(char *hands) { - int i, straightflush1 = 0, straightflush2 = 0, four1 = 0, four2 = 0, full1 = 0, full2 = 0, flush1 = 0, flush2 = 0; - int straight1 = 0, straight2 = 0, three1 = 0, three2 = 0, twopairs1 = 0, twopairs2 = 0; - int pair1 = 0, pair2 = 0; - char *card; - Card **cards1, **cards2; - values value; + int i, straightflush1 = 0, straightflush2 = 0, four1 = 0, four2 = 0, full1 = 0, full2 = 0, flush1 = 0, flush2 = 0; + int straight1 = 0, straight2 = 0, three1 = 0, three2 = 0, twopairs1 = 0, twopairs2 = 0; + int pair1 = 0, pair2 = 0; + char *card; + Card **cards1, **cards2; + values value; - if((cards1 = (Card **)malloc(5*sizeof(Card *))) == NULL || - (cards2 = (Card **)malloc(5*sizeof(Card *))) == NULL) - { - fprintf(stderr, "Error while allocating memory\n"); - exit(1); - } + if((cards1 = (Card **)malloc(5*sizeof(Card *))) == NULL || + (cards2 = (Card **)malloc(5*sizeof(Card *))) == NULL) + { + fprintf(stderr, "Error while allocating memory\n"); + exit(1); + } - for(i = 0; i < 5; i++) - { - if((cards1[i] = (Card *)malloc(sizeof(Card))) == NULL || - (cards2[i] = (Card *)malloc(sizeof(Card))) == NULL) - { - fprintf(stderr, "Error while allocating memory\n"); - exit(1); - } - } + for(i = 0; i < 5; i++) + { + if((cards1[i] = (Card *)malloc(sizeof(Card))) == NULL || + (cards2[i] = (Card *)malloc(sizeof(Card))) == NULL) + { + fprintf(stderr, "Error while allocating memory\n"); + exit(1); + } + } - card = strtok(hands, " "); + card = strtok(hands, " "); - /* Get current hand for player 1.*/ - get_value(cards1[0], card[0]); - cards1[0]->suit = card[1]; + /* Get current hand for player 1.*/ + get_value(cards1[0], card[0]); + cards1[0]->suit = card[1]; - for(i = 1; i < 5; i++) - { - card = strtok(NULL, " "); - get_value(cards1[i], card[0]); - cards1[i]->suit = card[1]; - } + for(i = 1; i < 5; i++) + { + card = strtok(NULL, " "); + get_value(cards1[i], card[0]); + cards1[i]->suit = card[1]; + } - /* Get current hand for player 2.*/ - for(i = 0; i < 5; i++) - { - card = strtok(NULL, " "); - get_value(cards2[i], card[0]); - cards2[i]->suit = card[1]; - } + /* Get current hand for player 2.*/ + for(i = 0; i < 5; i++) + { + card = strtok(NULL, " "); + get_value(cards2[i], card[0]); + cards2[i]->suit = card[1]; + } - /* Sort the two hands by value of the cards to make the evaluation easier.*/ - insertion_sort((void **)cards1, 0, 4, compare); - insertion_sort((void **)cards2, 0, 4, compare); + /* Sort the two hands by value of the cards to make the evaluation easier.*/ + insertion_sort((void **)cards1, 0, 4, compare); + insertion_sort((void **)cards2, 0, 4, compare); - /* If player 1 has a Royal Flush, player 1 wins.*/ - if(cards1[4]->value == ace && cards1[3]->value == king && cards1[2]->value == queen && - - cards1[0]->suit == cards1[2]->suit && cards1[0]->suit == cards1[3]->suit && - cards1[0]->suit == cards1[4]->suit) - { - return 1; - } + /* If player 1 has a Royal Flush, player 1 wins.*/ + if(cards1[4]->value == ace && cards1[3]->value == king && cards1[2]->value == queen && - /* If player 2 has a Royal Flush, player 2 wins.*/ - if(cards2[4]->value == ace && cards2[3]->value == king && cards2[2]->value == queen && - cards2[1]->value == jack && cards2[0]->value == ten && cards2[0]->suit == cards2[1]->suit && - cards2[0]->suit == cards2[2]->suit && cards2[0]->suit == cards2[3]->suit && - cards2[0]->suit == cards2[4]->suit) - { - return -1; - } + cards1[0]->suit == cards1[2]->suit && cards1[0]->suit == cards1[3]->suit && + cards1[0]->suit == cards1[4]->suit) + { + return 1; + } - /* Check if player 1 has a straight flush.*/ - if(cards1[0]->suit == cards1[1]->suit && cards1[0]->suit == cards1[2]->suit && cards1[0]->suit == cards1[3]->suit && - cards1[0]->suit == cards1[4]->suit) - { - value = cards1[0]->value; + /* If player 2 has a Royal Flush, player 2 wins.*/ + if(cards2[4]->value == ace && cards2[3]->value == king && cards2[2]->value == queen && + cards2[1]->value == jack && cards2[0]->value == ten && cards2[0]->suit == cards2[1]->suit && + cards2[0]->suit == cards2[2]->suit && cards2[0]->suit == cards2[3]->suit && + cards2[0]->suit == cards2[4]->suit) + { + return -1; + } - for(i = 1; i < 5; i++) - { - if(++value != cards1[i]->value) - { - break; - } - } + /* Check if player 1 has a straight flush.*/ + if(cards1[0]->suit == cards1[1]->suit && cards1[0]->suit == cards1[2]->suit && cards1[0]->suit == cards1[3]->suit && + cards1[0]->suit == cards1[4]->suit) + { + value = cards1[0]->value; - if(i == 5) - { - straightflush1 = 1; - } - } + for(i = 1; i < 5; i++) + { + if(++value != cards1[i]->value) + { + break; + } + } - /* Check if player 2 has a straight flush.*/ - if(cards2[0]->suit == cards2[1]->suit && cards2[0]->suit == cards2[2]->suit && - cards2[0]->suit == cards2[3]->suit && cards2[0]->suit == cards2[4]->suit) - { - value = cards2[0]->value; + if(i == 5) + { + straightflush1 = 1; + } + } - for(i = 1; i < 5; i++) - { - if(++value != cards2[i]->value) - { - break; - } - } + /* Check if player 2 has a straight flush.*/ + if(cards2[0]->suit == cards2[1]->suit && cards2[0]->suit == cards2[2]->suit && + cards2[0]->suit == cards2[3]->suit && cards2[0]->suit == cards2[4]->suit) + { + value = cards2[0]->value; - if(i == 5) - { - straightflush2=1; - } - } + for(i = 1; i < 5; i++) + { + if(++value != cards2[i]->value) + { + break; + } + } - /* If player 1 has a straight flush and player 2 doesn't, player 1 wins.*/ - if(straightflush1 && !straightflush2) - { - return 1; - } + if(i == 5) + { + straightflush2=1; + } + } - /* If player 2 has a straight flush and player 1 doesn't, player 2 wins.*/ - if(!straightflush1 && straightflush2) - { - return -1; - } + /* If player 1 has a straight flush and player 2 doesn't, player 1 wins.*/ + if(straightflush1 && !straightflush2) + { + return 1; + } - /* If both players have a straight flush, the one with the highest value wins. - * Any card can be compared, because in the straight flush the values are consecutive - * by definition.*/ - if(straightflush1 && straightflush2) - { - if(cards1[0]->value > cards2[0]->value) - { - return 1; - } - else - { - return -1; - } - } + /* If player 2 has a straight flush and player 1 doesn't, player 2 wins.*/ + if(!straightflush1 && straightflush2) + { + return -1; + } - /* Check if player 1 has four of a kind. Since cards are ordered, it is sufficient - * to check if the first card is equal to the fourth or if the second is equal to the fifth.*/ - if(cards1[0]->value == cards1[3]-> value || cards1[1]->value == cards1[4]->value) - { - four1 = 1; - } - - /* Check if player 2 has four of a kind.*/ - if(cards2[0]->value == cards2[3]->value || cards2[1]->value == cards2[4]->value) - { - four2 = 1; - } - - /* If player 1 has four of a kind and player 2 doesn't, player 1 wins.*/ - if(four1 && !four2) - { - return 1; - } - - /* If player 2 has four of a kind and player 1 doesn't, player 2 wins.*/ - if(!four1 && four2) - { - return -1; - } - - /* If both players have four of a kind, check who has the highest value for - * those four cards.*/ - if(four1 && four2) - { - if(cards1[1]->value > cards2[1]->value) - { - return 1; - } - if(cards1[1]->value < cards2[1]->value) - { - return -1; - } - } - - /* Check if player 1 has a full house.*/ - if(cards1[0]->value == cards1[1]->value && cards1[3]->value == cards1[4]->value && - (cards1[1]->value == cards1[2]->value || cards1[2]->value == cards1[3]->value)) - { - full1 = 1; - } - - /* Check if player 2 has a full house.*/ - if(cards2[0]->value == cards2[1]->value && cards2[3]->value == cards2[4]->value && - (cards2[1]->value == cards2[2]->value || cards2[2]->value == cards2[3]->value)) - { - full2 = 1; - } - - /* If player 1 has a full house and player 2 doesn't, player 1 wins.*/ - if(full1 && !full2) - { - return 1; - } - - /* If player 2 has a full house and player 1 doesn't, player 2 wins.*/ - if(!full1 && full2) - { - return -1; - } - - /* If both players have a full house, check who has the highest value - * for the three equal cards (the third card in the array will be part - * of the set of three).*/ - if(full1 && full2) - { - if(cards1[2]->value > cards2[2]->value) - { - return 1; - } - - if(cards1[2]->value < cards2[2]->value) - { - return -1; - } - } - - /* Check if player 1 has a flush.*/ - if(cards1[0]->suit == cards1[1]->suit && cards1[0]->suit == cards1[2]->suit && - cards1[0]->suit == cards1[3]->suit && cards1[0]->suit == cards1[4]->suit) - { - flush1 = 1; - } - - /* Check if player 2 has a flush.*/ - if(cards2[0]->suit == cards2[1]->suit && cards2[0]->suit == cards2[2]->suit && - cards2[0]->suit == cards2[3]->suit && cards2[0]->suit == cards2[4]->suit) - { - flush2 = 1; - } - - /* If player 1 has a flush and player 2 doesn't, player 1 wins.*/ - if(flush1 && !flush2) - { - return 1; - } - - /* If player 2 has a flush and player 1 doesn't, player 2 wins.*/ - if(!flush1 && flush2) - { - return -1; - } - - /* Check if player 1 has a straight.*/ - value = cards1[0]->value; - - for(i = 1; i < 5; i++) - { - if(++value != cards1[i]->value) - { - break; - } - } - - if(i == 5) - { - straight1 = 1; - } - - /* Check if player 2 has a straight.*/ - value = cards2[0]->value; - - for(i = 1; i < 5; i++) - { - if(++value != cards2[i]->value) - { - break; - } - } - - if(i == 5) - { - straight2 = 1; - } - - /* If player 1 has a straight and player 2 doesn't, player 1 wins.*/ - if(straight1 && !straight2) - { - return 1; - } - - /* If player 2 has a straight and player 1 doesn't, player 2 wins.*/ - if(!straight1 && straight2) - { - return -1; - } - - /* Check if player 1 has three of a kind.*/ - if((cards1[0]->value == cards1[1]->value && cards1[0]->value == cards1[2]->value) || - (cards1[1]->value == cards1[2]->value && cards1[1]->value == cards1[3]->value) || - (cards1[2]->value == cards1[3]->value && cards1[2]->value == cards1[4]->value)) - { - three1 = 1; - } - - /* Check if player 2 has three of a kind.*/ - if((cards2[0]->value == cards2[1]->value && cards2[0]->value == cards2[2]->value) || - (cards2[1]->value == cards2[2]->value && cards2[1]->value == cards2[3]->value) || - (cards2[2]->value == cards2[3]->value && cards2[2]->value == cards2[4]->value)) - { - three2 = 1; - } - - /* If player 1 has three of a kind and player 2 doesn't, player 1 wins.*/ - if(three1 && !three2) - { - return 1; - } - - /* If player 2 has three of a kind and player 1 doesn't, player 2 wins.*/ - if(!three1 && three2) - { - return -1; - } - - /* If both players have three of a kind, check who has the highest value for - * these three cards.*/ - if(three1 && three2) - { - if(cards1[2]->value > cards2[2]->value) - { - return 1; - } - - if(cards1[2]->value < cards2[2]->value) - { - return -1; - } - } - - /* Check if player 1 has two pairs.*/ - if((cards1[0]->value == cards1[1]->value && cards1[2]->value == cards1[3]->value) || - (cards1[0]->value == cards1[1]->value && cards1[3]->value == cards1[4]->value) || - (cards1[1]->value == cards1[2]->value && cards1[3]->value == cards1[4]->value)) - { - twopairs1 = 1; - } - - /* Check if player 2 has two pairs.*/ - if((cards2[0]->value == cards2[1]->value && cards2[2]->value == cards2[3]->value) || - (cards2[0]->value == cards2[1]->value && cards2[3]->value == cards2[4]->value) || - (cards2[1]->value == cards2[2]->value && cards2[3]->value == cards2[4]->value)) - { - twopairs2 = 1; - } - - /* If player 1 has two pairs and player 2 doesn't, player 1 wins.*/ - if(twopairs1 && !twopairs2) - { - return 1; - } - - /* If player 2 has two pairs and player 1 doesn't, player 2 wins.*/ - if(!twopairs1 && twopairs2) - { - return -1; - } - - /* If both players have two pairs, check who has the highest pair. If it's equal, - * check the other pair. If it's still equal, check the remaining card.*/ - if(twopairs1 && twopairs2) - { - if(cards1[3]->value > cards2[3]->value) - { - return 1; - } - else if(cards1[3]->value < cards2[3]->value) - { - return -1; - } - else if(cards1[1]->value > cards2[1]->value) - { - return 1; - } - else if(cards1[1]->value < cards2[1]->value) - { - return -1; - } - - for(i = 4; i >= 0; i--) - { - if(cards1[i]->value > cards2[i]->value) - { + /* If both players have a straight flush, the one with the highest value wins. + * Any card can be compared, because in the straight flush the values are consecutive + * by definition.*/ + if(straightflush1 && straightflush2) + { + if(cards1[0]->value > cards2[0]->value) + { return 1; - } - - if(cards1[i]->value < cards2[i]->value) - { + } + else + { return -1; - } - } - } + } + } - /* Check if player 1 has a pair of cards*/ - if(cards1[0]->value == cards1[1]->value || cards1[1]->value == cards1[2]->value || - cards1[2]->value == cards1[3]->value || cards1[3]->value == cards1[4]->value) - { - pair1 = 1; - } + /* Check if player 1 has four of a kind. Since cards are ordered, it is sufficient + * to check if the first card is equal to the fourth or if the second is equal to the fifth.*/ + if(cards1[0]->value == cards1[3]-> value || cards1[1]->value == cards1[4]->value) + { + four1 = 1; + } - /* Check if player 2 has a pair of cards.*/ - if(cards2[0]->value == cards2[1]->value || cards2[1]->value == cards2[2]->value || - cards2[2]->value == cards2[3]->value || cards2[3]->value == cards2[4]->value) - { - pair2 = 1; - } + /* Check if player 2 has four of a kind.*/ + if(cards2[0]->value == cards2[3]->value || cards2[1]->value == cards2[4]->value) + { + four2 = 1; + } - /* If player 1 has a pair of cards and player 2 doesn't, player 1 wins.*/ - if(pair1 && !pair2) - { - return 1; - } + /* If player 1 has four of a kind and player 2 doesn't, player 1 wins.*/ + if(four1 && !four2) + { + return 1; + } - /* If player 2 has a pair of cards and player 1 doesn't, player 2 wins.*/ - if(!pair1 && pair2) - { - return -1; - } + /* If player 2 has four of a kind and player 1 doesn't, player 2 wins.*/ + if(!four1 && four2) + { + return -1; + } - /* If both players have a pair of cards, check who has the highest pair. Since the cards are - * ordered by value, either card[1] will be part of the pair (card[0]=card[1] or - * card[1]=card[2]) or card[3] will be part of the pair (card[2]=card[3] or - * card[3]=card[4]). */ - if(pair1 && pair2) - { - if(cards1[0]->value == cards1[1]->value || cards1[1]->value == cards1[2]->value) - { - value = cards1[1]->value; + /* If both players have four of a kind, check who has the highest value for + * those four cards.*/ + if(four1 && four2) + { + if(cards1[1]->value > cards2[1]->value) + { + return 1; + } + if(cards1[1]->value < cards2[1]->value) + { + return -1; + } + } - if(cards2[0]->value == cards2[1]->value || cards2[1]->value == cards2[2]->value) - { - if(value > cards2[1]->value) + /* Check if player 1 has a full house.*/ + if(cards1[0]->value == cards1[1]->value && cards1[3]->value == cards1[4]->value && + (cards1[1]->value == cards1[2]->value || cards1[2]->value == cards1[3]->value)) + { + full1 = 1; + } + + /* Check if player 2 has a full house.*/ + if(cards2[0]->value == cards2[1]->value && cards2[3]->value == cards2[4]->value && + (cards2[1]->value == cards2[2]->value || cards2[2]->value == cards2[3]->value)) + { + full2 = 1; + } + + /* If player 1 has a full house and player 2 doesn't, player 1 wins.*/ + if(full1 && !full2) + { + return 1; + } + + /* If player 2 has a full house and player 1 doesn't, player 2 wins.*/ + if(!full1 && full2) + { + return -1; + } + + /* If both players have a full house, check who has the highest value + * for the three equal cards (the third card in the array will be part + * of the set of three).*/ + if(full1 && full2) + { + if(cards1[2]->value > cards2[2]->value) + { + return 1; + } + + if(cards1[2]->value < cards2[2]->value) + { + return -1; + } + } + + /* Check if player 1 has a flush.*/ + if(cards1[0]->suit == cards1[1]->suit && cards1[0]->suit == cards1[2]->suit && + cards1[0]->suit == cards1[3]->suit && cards1[0]->suit == cards1[4]->suit) + { + flush1 = 1; + } + + /* Check if player 2 has a flush.*/ + if(cards2[0]->suit == cards2[1]->suit && cards2[0]->suit == cards2[2]->suit && + cards2[0]->suit == cards2[3]->suit && cards2[0]->suit == cards2[4]->suit) + { + flush2 = 1; + } + + /* If player 1 has a flush and player 2 doesn't, player 1 wins.*/ + if(flush1 && !flush2) + { + return 1; + } + + /* If player 2 has a flush and player 1 doesn't, player 2 wins.*/ + if(!flush1 && flush2) + { + return -1; + } + + /* Check if player 1 has a straight.*/ + value = cards1[0]->value; + + for(i = 1; i < 5; i++) + { + if(++value != cards1[i]->value) + { + break; + } + } + + if(i == 5) + { + straight1 = 1; + } + + /* Check if player 2 has a straight.*/ + value = cards2[0]->value; + + for(i = 1; i < 5; i++) + { + if(++value != cards2[i]->value) + { + break; + } + } + + if(i == 5) + { + straight2 = 1; + } + + /* If player 1 has a straight and player 2 doesn't, player 1 wins.*/ + if(straight1 && !straight2) + { + return 1; + } + + /* If player 2 has a straight and player 1 doesn't, player 2 wins.*/ + if(!straight1 && straight2) + { + return -1; + } + + /* Check if player 1 has three of a kind.*/ + if((cards1[0]->value == cards1[1]->value && cards1[0]->value == cards1[2]->value) || + (cards1[1]->value == cards1[2]->value && cards1[1]->value == cards1[3]->value) || + (cards1[2]->value == cards1[3]->value && cards1[2]->value == cards1[4]->value)) + { + three1 = 1; + } + + /* Check if player 2 has three of a kind.*/ + if((cards2[0]->value == cards2[1]->value && cards2[0]->value == cards2[2]->value) || + (cards2[1]->value == cards2[2]->value && cards2[1]->value == cards2[3]->value) || + (cards2[2]->value == cards2[3]->value && cards2[2]->value == cards2[4]->value)) + { + three2 = 1; + } + + /* If player 1 has three of a kind and player 2 doesn't, player 1 wins.*/ + if(three1 && !three2) + { + return 1; + } + + /* If player 2 has three of a kind and player 1 doesn't, player 2 wins.*/ + if(!three1 && three2) + { + return -1; + } + + /* If both players have three of a kind, check who has the highest value for + * these three cards.*/ + if(three1 && three2) + { + if(cards1[2]->value > cards2[2]->value) + { + return 1; + } + + if(cards1[2]->value < cards2[2]->value) + { + return -1; + } + } + + /* Check if player 1 has two pairs.*/ + if((cards1[0]->value == cards1[1]->value && cards1[2]->value == cards1[3]->value) || + (cards1[0]->value == cards1[1]->value && cards1[3]->value == cards1[4]->value) || + (cards1[1]->value == cards1[2]->value && cards1[3]->value == cards1[4]->value)) + { + twopairs1 = 1; + } + + /* Check if player 2 has two pairs.*/ + if((cards2[0]->value == cards2[1]->value && cards2[2]->value == cards2[3]->value) || + (cards2[0]->value == cards2[1]->value && cards2[3]->value == cards2[4]->value) || + (cards2[1]->value == cards2[2]->value && cards2[3]->value == cards2[4]->value)) + { + twopairs2 = 1; + } + + /* If player 1 has two pairs and player 2 doesn't, player 1 wins.*/ + if(twopairs1 && !twopairs2) + { + return 1; + } + + /* If player 2 has two pairs and player 1 doesn't, player 2 wins.*/ + if(!twopairs1 && twopairs2) + { + return -1; + } + + /* If both players have two pairs, check who has the highest pair. If it's equal, + * check the other pair. If it's still equal, check the remaining card.*/ + if(twopairs1 && twopairs2) + { + if(cards1[3]->value > cards2[3]->value) + { + return 1; + } + else if(cards1[3]->value < cards2[3]->value) + { + return -1; + } + else if(cards1[1]->value > cards2[1]->value) + { + return 1; + } + else if(cards1[1]->value < cards2[1]->value) + { + return -1; + } + + for(i = 4; i >= 0; i--) + { + if(cards1[i]->value > cards2[i]->value) { - return 1; + return 1; } - if(value < cards2[1]->value) + if(cards1[i]->value < cards2[i]->value) { - return -1; + return -1; } - } + } + } - if(cards2[2]->value == cards2[3]->value || cards2[3]->value == cards2[4]->value) - { - if(value > cards2[3]->value) + /* Check if player 1 has a pair of cards*/ + if(cards1[0]->value == cards1[1]->value || cards1[1]->value == cards1[2]->value || + cards1[2]->value == cards1[3]->value || cards1[3]->value == cards1[4]->value) + { + pair1 = 1; + } + + /* Check if player 2 has a pair of cards.*/ + if(cards2[0]->value == cards2[1]->value || cards2[1]->value == cards2[2]->value || + cards2[2]->value == cards2[3]->value || cards2[3]->value == cards2[4]->value) + { + pair2 = 1; + } + + /* If player 1 has a pair of cards and player 2 doesn't, player 1 wins.*/ + if(pair1 && !pair2) + { + return 1; + } + + /* If player 2 has a pair of cards and player 1 doesn't, player 2 wins.*/ + if(!pair1 && pair2) + { + return -1; + } + + /* If both players have a pair of cards, check who has the highest pair. Since the cards are + * ordered by value, either card[1] will be part of the pair (card[0]=card[1] or + * card[1]=card[2]) or card[3] will be part of the pair (card[2]=card[3] or + * card[3]=card[4]). */ + if(pair1 && pair2) + { + if(cards1[0]->value == cards1[1]->value || cards1[1]->value == cards1[2]->value) + { + value = cards1[1]->value; + + if(cards2[0]->value == cards2[1]->value || cards2[1]->value == cards2[2]->value) { - return 1; + if(value > cards2[1]->value) + { + return 1; + } + + if(value < cards2[1]->value) + { + return -1; + } } - if(value < cards2[3]->value) + if(cards2[2]->value == cards2[3]->value || cards2[3]->value == cards2[4]->value) { - return -1; + if(value > cards2[3]->value) + { + return 1; + } + + if(value < cards2[3]->value) + { + return -1; + } } - } - } - else - { - value = cards1[3]->value; - - if(cards2[0]->value == cards2[1]->value || cards2[1]->value == cards2[2]->value) - { - if(value > cards2[1]->value) + } + else + { + value = cards1[3]->value; + + if(cards2[0]->value == cards2[1]->value || cards2[1]->value == cards2[2]->value) { - return 1; - } + if(value > cards2[1]->value) + { + return 1; + } - if(value < cards2[1]->value) + if(value < cards2[1]->value) + { + return -1; + } + } + else if(cards2[2]->value == cards2[3]->value || cards2[3]->value == cards2[4]->value) { - return -1; - } - } - else if(cards2[2]->value == cards2[3]->value || cards2[3]->value == cards2[4]->value) - { - if(value > cards2[3]->value) - { - return 1; + if(value > cards2[3]->value) + { + return 1; + } + + if(value < cards2[3]->value) + { + return -1; + } } + } + } - if(value < cards2[3]->value) - { - return -1; - } - } - } - } + /* If all other things are equal, check who has the highest card, if it's equal check the second highest and so on.*/ + for(i = 4; i >= 0; i--) + { + if(cards1[i]->value > cards2[i]->value) + { + return 1; + } - /* If all other things are equal, check who has the highest card, if it's equal check the second highest and so on.*/ - for(i = 4; i >= 0; i--) - { - if(cards1[i]->value > cards2[i]->value) - { - return 1; - } + if(cards1[i]->value < cards2[i]->value) + { + return -1; + } + } - if(cards1[i]->value < cards2[i]->value) - { - return -1; - } - } - - /* If everything is equal, return 0.*/ - return 0; + /* If everything is equal, return 0.*/ + return 0; } diff --git a/C/p055.c b/C/p055.c index 0117caa..8c1f144 100644 --- a/C/p055.c +++ b/C/p055.c @@ -9,8 +9,8 @@ * That is, 349 took three iterations to arrive at a palindrome. * * Although no one has proved it yet, it is thought that some numbers, like 196, never produce a palindrome. A number that never forms a palindrome - * through the reverse and add process is called a Lychrel number. Due to the theoretical nature of these numbers, and for the purpose of this problem, - * we shall assume that a number is Lychrel until proven otherwise. In addition you are given that for every number below ten-thousand, it will either + * through the reverse and add process is called a Lychrel number. Due to the theoretical nature of these numbers, and for the purpose of this problem, + * we shall assume that a number is Lychrel until proven otherwise. In addition you are given that for every number below ten-thousand, it will either * (i) become a palindrome in less than fifty iterations, or, * (ii) no one, with all the computing power that exists, has managed so far to map it to a palindrome. In fact, 10677 is the first number to be shown * to require over fifty iterations before producing a palindrome: 4668731596684224866951378664 (53 iterations, 28-digits). @@ -21,6 +21,8 @@ * * NOTE: Wording was modified slightly on 24 April 2007 to emphasise the theoretical nature of Lychrel numbers.*/ +#define _POSIX_C_SOURCE 199309L + #include #include #include @@ -31,73 +33,73 @@ int is_lychrel(mpz_t n); int main(int argc, char **argv) { - int i, count = 0; - double elapsed; - struct timespec start, end; - mpz_t n; + int i, count = 0; + double elapsed; + struct timespec start, end; + 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 - * is a Lychrel number.*/ - for(i = 1; i < 10000; i++) - { - mpz_set_ui(n, i); + /* For each number, use the is_lychrel function to check if the number + * is a Lychrel number.*/ + for(i = 1; i < 10000; i++) + { + mpz_set_ui(n, i); - if(is_lychrel(n)) - count++; - } + if(is_lychrel(n)) + count++; + } - mpz_clear(n); - clock_gettime(CLOCK_MONOTONIC, &end); + mpz_clear(n); + 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("Answer: %d\n", count); + printf("Project Euler, Problem 55\n"); + 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 i; - mpz_t tmp, reverse, rem; + int i; + mpz_t tmp, reverse, rem; - mpz_inits(tmp, reverse, rem, NULL); - mpz_set(tmp, n); + mpz_inits(tmp, reverse, rem, NULL); + mpz_set(tmp, n); - /* Run for 50 iterations.*/ - for(i = 0; i < 50; i++) - { - mpz_set_ui(reverse, 0); + /* Run for 50 iterations.*/ + for(i = 0; i < 50; i++) + { + mpz_set_ui(reverse, 0); - /* Find the reverse of the given number.*/ - while(mpz_cmp_ui(tmp, 0) > 0) - { - mpz_mul_ui(reverse, reverse, 10); - mpz_tdiv_qr_ui(tmp, rem, tmp, 10); - mpz_add(reverse, reverse, rem); - } + /* Find the reverse of the given number.*/ + while(mpz_cmp_ui(tmp, 0) > 0) + { + mpz_mul_ui(reverse, reverse, 10); + mpz_tdiv_qr_ui(tmp, rem, tmp, 10); + mpz_add(reverse, reverse, rem); + } - /* Add the reverse to the original number.*/ - mpz_add(tmp, n, reverse); + /* Add the reverse to the original number.*/ + mpz_add(tmp, n, reverse); - /* If the sum is a palindrome, the number is not a Lychrel number.*/ - if(is_palindrome_mpz(tmp, 10)) - { - mpz_clears(tmp, reverse, rem, NULL); - return 0; - } + /* If the sum is a palindrome, the number is not a Lychrel number.*/ + if(is_palindrome_mpz(tmp, 10)) + { + mpz_clears(tmp, reverse, rem, NULL); + 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; } diff --git a/C/p056.c b/C/p056.c index 314964c..abd3851 100644 --- a/C/p056.c +++ b/C/p056.c @@ -3,6 +3,8 @@ * * Considering natural numbers of the form, a^b, where a, b < 100, what is the maximum digital sum?*/ +#define _POSIX_C_SOURCE 199309L + #include #include #include @@ -10,41 +12,41 @@ int main(int argc, char **argv) { - int a, b, sum, max = 0; - double elapsed; - struct timespec start, end; - mpz_t pow; + int a, b, sum, max = 0; + double elapsed; + struct timespec start, end; + 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.*/ - for(a = 1; a < 100; a++) - { - for(b = 1; b < 100; b++) - { - mpz_ui_pow_ui(pow, a, b); - sum = 0; + /* Straightforward brute force approach using the GMP Library.*/ + for(a = 1; a < 100; a++) + { + for(b = 1; b < 100; b++) + { + mpz_ui_pow_ui(pow, a, b); + sum = 0; - while(mpz_cmp_ui(pow, 0)) - sum += mpz_tdiv_q_ui(pow, pow, 10); + while(mpz_cmp_ui(pow, 0)) + sum += mpz_tdiv_q_ui(pow, pow, 10); - if(sum > max) - max = sum; - } - } + if(sum > max) + 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("Answer: %d\n", max); + printf("Project Euler, Problem 56\n"); + printf("Answer: %d\n", max); - printf("Elapsed time: %.9lf seconds\n", elapsed); + printf("Elapsed time: %.9lf seconds\n", elapsed); - return 0; + return 0; } diff --git a/C/p057.c b/C/p057.c index f7d6aef..22dd77e 100644 --- a/C/p057.c +++ b/C/p057.c @@ -14,6 +14,8 @@ * * In the first one-thousand expansions, how many fractions contain a numerator with more digits than the denominator?*/ +#define _POSIX_C_SOURCE 199309L + #include #include #include @@ -23,64 +25,64 @@ int count_digits(mpz_t n); int main(int argc, char **argv) { - int i, count = 0; - mpz_t n, d, d2; - double elapsed; - struct timespec start, end; + int i, count = 0; + mpz_t n, d, d2; + double elapsed; + struct timespec start, end; - clock_gettime(CLOCK_MONOTONIC, &start); + clock_gettime(CLOCK_MONOTONIC, &start); - mpz_init_set_ui(n, 1); - mpz_init_set_ui(d, 1); - mpz_init(d2); + mpz_init_set_ui(n, 1); + mpz_init_set_ui(d, 1); + mpz_init(d2); - /* 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.*/ - for(i = 1; i < 1000; i++) - { - mpz_mul_ui(d2, d, 2); - mpz_add(d, n, d); - mpz_add(n, n, d2); + /* 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.*/ + for(i = 1; i < 1000; i++) + { + mpz_mul_ui(d2, d, 2); + mpz_add(d, n, d); + mpz_add(n, n, d2); - if(count_digits(n) > count_digits(d)) - { - count++; - } - } + if(count_digits(n) > count_digits(d)) + { + 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("Answer: %d\n", count); + printf("Project Euler, Problem 57\n"); + 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 = 0; - mpz_t value; + int count = 0; + mpz_t value; - if(mpz_cmp_ui(n, 0) == 0) - { - return 1; - } + if(mpz_cmp_ui(n, 0) == 0) + { + return 1; + } - mpz_init_set(value, n); + mpz_init_set(value, n); - while(mpz_cmp_ui(value, 0)) - { - mpz_tdiv_q_ui(value, value, 10); - count++; - } + while(mpz_cmp_ui(value, 0)) + { + mpz_tdiv_q_ui(value, value, 10); + count++; + } - mpz_clear(value); + mpz_clear(value); - return count; + return count; } diff --git a/C/p058.c b/C/p058.c index f8bce19..625c571 100644 --- a/C/p058.c +++ b/C/p058.c @@ -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, * 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 #include #include @@ -22,57 +24,57 @@ int main(int argc, char **argv) { - int i = 1, l = 1, step = 2, count = 0, diag = 5; - double ratio, elapsed; - struct timespec start, end; + int i = 1, l = 1, step = 2, count = 0, diag = 5; + double ratio, elapsed; + 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) - * 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 - * 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.*/ - do - { - i += step; + /* 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 + * 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. + * Then 25+6 etc., at every cycle the step is increased by 2. Continue until the ratio goes below 0.1.*/ + do + { + i += step; - if(is_prime(i)) - { - count++; - } + if(is_prime(i)) + { + count++; + } - i += step; + i += step; - if(is_prime(i)) - { - count++; - } + if(is_prime(i)) + { + count++; + } - i += step; + i += step; - if(is_prime(i)) - { - count++; - } + if(is_prime(i)) + { + count++; + } - i += step; - ratio = (double)count / diag; + i += step; + ratio = (double)count / diag; - step += 2; - diag += 4; - l += 2; + step += 2; + diag += 4; + 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("Answer: %d\n", l); + printf("Project Euler, Problem 58\n"); + printf("Answer: %d\n", l); - printf("Elapsed time: %.9lf seconds\n", elapsed); + printf("Elapsed time: %.9lf seconds\n", elapsed); - return 0; + return 0; } diff --git a/C/p059.c b/C/p059.c index 6be47b6..5d69702 100644 --- a/C/p059.c +++ b/C/p059.c @@ -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 * ASCII values in the original text.*/ +#define _POSIX_C_SOURCE 199309L + #include #include #include diff --git a/C/p060.c b/C/p060.c index 15ecf0c..a2d7f6f 100644 --- a/C/p060.c +++ b/C/p060.c @@ -4,6 +4,8 @@ * * 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 #include #include @@ -18,97 +20,97 @@ int *primes; int main(int argc, char **argv) { - int found = 0, p1, p2, p3, p4, p5, n; - double elapsed; - struct timespec start, end; + int found = 0, p1, p2, p3, p4, p5, n; + double elapsed; + struct timespec start, end; - clock_gettime(CLOCK_MONOTONIC, &start); + clock_gettime(CLOCK_MONOTONIC, &start); - if((primes = sieve(N)) == NULL) - { - fprintf(stderr, "Error! Sieve function returned NULL\n"); - return 1; - } + if((primes = sieve(N)) == NULL) + { + fprintf(stderr, "Error! Sieve function returned NULL\n"); + return 1; + } - /* Straightforward brute force approach.*/ - for(p1 = 3; p1 < N && !found; p1 += 2) - { - /* If p1 is not prime, go to the next number.*/ - 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))) - { + /* Straightforward brute force approach.*/ + for(p1 = 3; p1 < N && !found; p1 += 2) + { + /* If p1 is not prime, go to the next number.*/ + if(!primes[p1]) + { continue; - } + } - for(p3 = p2 + 2; p3 < N && !found; p3 += 2) - { - /* If p3 is not prime, or at least one of the possible concatenations of - * p1, p2 and p3 is not prime, go to the next number.*/ - if(!primes[p3] || !is_prime(cat(p1, p3)) || !is_prime(cat(p3, p1)) || - !is_prime(cat(p2, p3)) || !is_prime(cat(p3, p2))) + 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(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 - * p1, p2, p3 and p4 is not prime, go to the next number.*/ - if(!primes[p4] || !is_prime(cat(p1, p4)) || !is_prime(cat(p4, p1)) || - !is_prime(cat(p2, p4)) || !is_prime(cat(p4, p2)) || - !is_prime(cat(p3, p4)) || !is_prime(cat(p4, p3))) - { - continue; - } + /* If p3 is not prime, or at least one of the possible concatenations of + * p1, p2 and p3 is not prime, go to the next number.*/ + if(!primes[p3] || !is_prime(cat(p1, p3)) || !is_prime(cat(p3, p1)) || + !is_prime(cat(p2, p3)) || !is_prime(cat(p3, p2))) + { + continue; + } - for(p5 = p4 + 2; p5 < N && !found; p5 += 2) - { - /* 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; - } + for(p4 = p3 + 2; p4 < N && !found; p4 += 2) + { + /* If p4 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.*/ + if(!primes[p4] || !is_prime(cat(p1, p4)) || !is_prime(cat(p4, p1)) || + !is_prime(cat(p2, p4)) || !is_prime(cat(p4, p2)) || + !is_prime(cat(p3, p4)) || !is_prime(cat(p4, p3))) + { + continue; + } - /* If it gets here, the five values have been found.*/ - n = p1 + p2 + p3 + p4 + p5; - found = 1; - } + for(p5 = p4 + 2; p5 < N && !found; p5 += 2) + { + /* 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); - - elapsed=(end.tv_sec-start.tv_sec)+(double)(end.tv_nsec-start.tv_nsec)/1000000000; + clock_gettime(CLOCK_MONOTONIC, &end); - printf("Project Euler, Problem 60\n"); - printf("Answer: %d\n", n); + elapsed=(end.tv_sec-start.tv_sec)+(double)(end.tv_nsec-start.tv_nsec)/1000000000; - printf("Elapsed time: %.9lf seconds\n", elapsed); + printf("Project Euler, Problem 60\n"); + printf("Answer: %d\n", n); - return 0; + printf("Elapsed time: %.9lf seconds\n", elapsed); + + return 0; } 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); } diff --git a/C/p061.c b/C/p061.c index 0185e3d..6ee939a 100644 --- a/C/p061.c +++ b/C/p061.c @@ -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, * hexagonal, heptagonal, and octagonal, is represented by a different number in the set.*/ +#define _POSIX_C_SOURCE 199309L + #include #include #include @@ -28,94 +30,94 @@ int chain[6], flags[6] = {0}; int main(int argc, char **argv) { - int i, n, sum = 0; - double elapsed; - struct timespec start, end; + int i, n, sum = 0; + double elapsed; + struct timespec start, end; - clock_gettime(CLOCK_MONOTONIC, &start); + clock_gettime(CLOCK_MONOTONIC, &start); - i = 1; - n = 1; + i = 1; + n = 1; - /* Generate all triangle numbers smaller than 10000*/ - do - { - polygonal[0][n] = 1; - i++; - n = i * (i + 1) / 2; - }while(n < 10000); + /* Generate all triangle numbers smaller than 10000*/ + do + { + polygonal[0][n] = 1; + i++; + n = i * (i + 1) / 2; + } while(n < 10000); - i = 1; - n = 1; + i = 1; + n = 1; - /* Generate all square numbers smaller than 10000.*/ - do - { - polygonal[1][n] = 1; - i++; - n = i * i; - }while(n < 10000); + /* Generate all square numbers smaller than 10000.*/ + do + { + polygonal[1][n] = 1; + i++; + n = i * i; + } while(n < 10000); - i = 1; - n = 1; + i = 1; + n = 1; - /* Generate all pentagonal numbers smaller than 10000.*/ - do - { - polygonal[2][n] = 1; - i++; - n = i * (3 * i - 1) / 2; - }while(n < 10000); + /* Generate all pentagonal numbers smaller than 10000.*/ + do + { + polygonal[2][n] = 1; + i++; + n = i * (3 * i - 1) / 2; + } while(n < 10000); - i = 1; - n = 1; + i = 1; + n = 1; - /* Generate all hexagonal numbers smaller than 10000.*/ - do - { - polygonal[3][n] = 1; - i++; - n = i * (2 * i - 1); - }while(n < 10000); + /* Generate all hexagonal numbers smaller than 10000.*/ + do + { + polygonal[3][n] = 1; + i++; + n = i * (2 * i - 1); + } while(n < 10000); - i = 1; - n = 1; + i = 1; + n = 1; - /* Generate all heptagonal numbers smaller than 10000.*/ - do - { - polygonal[4][n] = 1; - i++; - n = i * (5 * i - 3) / 2; - }while(n < 10000); + /* Generate all heptagonal numbers smaller than 10000.*/ + do + { + polygonal[4][n] = 1; + i++; + n = i * (5 * i - 3) / 2; + } while(n < 10000); - i = 1; - n = 1; + i = 1; + n = 1; - /* Generate all octagonal numbers smaller than 10000.*/ - do - { - polygonal[5][n] = 1; - i++; - n = i * (3 * i - 2); - }while(n < 10000); + /* Generate all octagonal numbers smaller than 10000.*/ + do + { + polygonal[5][n] = 1; + i++; + n = i * (3 * i - 2); + } while(n < 10000); - /* Find the requested set of numbers.*/ - if(find_set(0, &sum) == 0) - { - printf("Set not found\n"); - } + /* Find the requested set of numbers.*/ + if(find_set(0, &sum) == 0) + { + 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("Answer: %d\n", sum); - - printf("Elapsed time: %.9lf seconds\n", elapsed); + printf("Project Euler, Problem 61\n"); + printf("Answer: %d\n", sum); - return 0; + printf("Elapsed time: %.9lf seconds\n", elapsed); + + return 0; } /* 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.*/ int find_set(int step, int *sum) { - int i, j; + int i, j; - /* Use one polygonal number per type, starting from triangular.*/ - for(i = 0; i < 6; i++) - { - /* If the current type has not been used yet, try it.*/ - if(!flags[i]) - { - /* Set a flag to record that the current polygonal type has been used.*/ - flags[i] = 1; + /* Use one polygonal number per type, starting from triangular.*/ + for(i = 0; i < 6; i++) + { + /* If the current type has not been used yet, try it.*/ + if(!flags[i]) + { + /* Set a flag to record that the current polygonal type has been used.*/ + flags[i] = 1; - /* Start from 1010 because numbers finishing with 00, 01, ..., 09 can't - * be part of the chain.*/ - 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]) + /* Start from 1010 because numbers finishing with 00, 01, ..., 09 can't + * be part of the chain.*/ + for(j = 1010; j < 10000; j++) { - /* If it's the first number, just add it as first step in the chain.*/ - if(step == 0) - { - chain[step] = j; - *sum += 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(step == 0) + { + chain[step] = j; + *sum += j; - /* Recursively try to add other numbers to the chain. If a solution - * is found, return 1.*/ - if(find_set(step+1, sum)) - { - return 1; - } + /* Recursively try to add other numbers to the chain. If a solution + * is found, return 1.*/ + if(find_set(step+1, sum)) + { + return 1; + } - /* If a solution was not found, backtrack, subtracting the value of - * the number from the total.*/ - *sum -= j; - } - /* 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.*/ - else if(step == 5 && j % 100 == chain[0] / 100 && j / 100 == chain[step-1] % 100) - { - chain[step] = j; - *sum += j; - return 1; - } - /* For every other step, add the number to the chain if possible, then recursively - * try to add other numbers.*/ - else if(step < 5 && j / 100 == chain[step-1] % 100) - { - chain[step] = j; - *sum += j; + /* If a solution was not found, backtrack, subtracting the value of + * the number from the total.*/ + *sum -= j; + } + /* 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.*/ + else if(step == 5 && j % 100 == chain[0] / 100 && j / 100 == chain[step-1] % 100) + { + chain[step] = j; + *sum += j; + return 1; + } + /* For every other step, add the number to the chain if possible, then recursively + * try to add other numbers.*/ + else if(step < 5 && j / 100 == chain[step-1] % 100) + { + chain[step] = j; + *sum += j; - if(find_set(step+1, sum)) - { - return 1; - } + if(find_set(step+1, sum)) + { + return 1; + } - /* If a solution was not found, backtrack.*/ - *sum -= j; - } + /* If a solution was not found, backtrack.*/ + *sum -= j; + } + } } - } - /* Remove the flag for the current polygonal type.*/ - flags[i] = 0; - } - } + /* Remove the flag for the current polygonal type.*/ + flags[i] = 0; + } + } - return 0; + return 0; } diff --git a/C/p062.c b/C/p062.c index 118374e..8a87e32 100644 --- a/C/p062.c +++ b/C/p062.c @@ -1,8 +1,10 @@ -/* The cube, 41063625 (345^3), can be permuted to produce two other cubes: 56623104 (384^3) and 66430125 (405^3). +/* The cube, 41063625 (345^3), can be permuted to produce two other cubes: 56623104 (384^3) and 66430125 (405^3). * In fact, 41063625 is the smallest cube which has exactly three permutations of its digits which are also cube. * * Find the smallest cube for which exactly five permutations of its digits are cube.*/ +#define _POSIX_C_SOURCE 199309L + #include #include #include @@ -14,104 +16,104 @@ int count_digits(long int a); int main(int argc, char **argv) { - int count; - long int i, j, cubes[N]; - double elapsed; - struct timespec start, end; + int count; + long int i, j, cubes[N]; + double elapsed; + struct timespec start, end; - clock_gettime(CLOCK_MONOTONIC, &start); + clock_gettime(CLOCK_MONOTONIC, &start); - /* Calculate i^3 for all i smaller than 10000.*/ - for(i = 0; i < N; i++) - { - cubes[i] = i * i * i; - } + /* Calculate i^3 for all i smaller than 10000.*/ + for(i = 0; i < N; i++) + { + cubes[i] = i * i * i; + } - /* For each cube, check if there are four other cubes which are also - * a permutation of the first cube.*/ - for(i = 0; i < N - 5; i++) - { - count = 1; + /* For each cube, check if there are four other cubes which are also + * a permutation of the first cube.*/ + for(i = 0; i < N - 5; i++) + { + count = 1; - /* 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, - * they can't be permutations).*/ - for(j = i + 1; j < N && count_digits(cubes[j]) == count_digits(cubes[i]); j++) - { - if(is_permutation(cubes[i], cubes[j])) - { - count++; - } + /* 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, + * they can't be permutations).*/ + for(j = i + 1; j < N && count_digits(cubes[j]) == count_digits(cubes[i]); j++) + { + if(is_permutation(cubes[i], cubes[j])) + { + count++; + } - if(count == 5) - { + if(count == 5) + { + break; + } + } + + if(count == 5) + { break; - } - } + } + } - if(count == 5) - { - 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 62\n"); + printf("Answer: %ld\n", cubes[i]); - printf("Project Euler, Problem 62\n"); - printf("Answer: %ld\n", cubes[i]); + printf("Elapsed time: %.9lf seconds\n", elapsed); - printf("Elapsed time: %.9lf seconds\n", elapsed); - - return 0; + return 0; } int count_digits(long int a) { - int count = 0; + int count = 0; - if(a == 0) - { - return 1; - } + if(a == 0) + { + return 1; + } - while(a > 0) - { - count++; - a /= 10; - } + while(a > 0) + { + count++; + a /= 10; + } - return count; + return count; } int is_permutation(long int a, long int b) { - int i; - int digits1[10] = {0}, digits2[10] = {0}; + int i; + int digits1[10] = {0}, digits2[10] = {0}; - /* Get digits of a.*/ - while(a > 0) - { - digits1[a%10]++; - a /= 10; - } + /* Get digits of a.*/ + while(a > 0) + { + digits1[a%10]++; + a /= 10; + } - /* Get digits of b.*/ - while(b > 0) - { - digits2[b%10]++; - b /= 10; - } + /* Get digits of b.*/ + while(b > 0) + { + digits2[b%10]++; + b /= 10; + } - /* If they're not the same, return 0.*/ - for(i = 0; i < 10; i++) - { - if(digits1[i] != digits2[i]) - { - return 0; - } - } + /* If they're not the same, return 0.*/ + for(i = 0; i < 10; i++) + { + if(digits1[i] != digits2[i]) + { + return 0; + } + } - return 1; + return 1; } diff --git a/C/p063.c b/C/p063.c index 9e1840f..3837233 100644 --- a/C/p063.c +++ b/C/p063.c @@ -2,6 +2,8 @@ * * How many n-digit positive integers exist which are also an nth power?*/ +#define _POSIX_C_SOURCE 199309L + #include #include #include @@ -12,70 +14,70 @@ int count_digits(mpz_t n); int main(int argc, char **argv) { - int i, j, count = 0, finished = 0; - double elapsed; - struct timespec start, end; - mpz_t p; + int i, j, count = 0, finished = 0; + double elapsed; + struct timespec start, end; + 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) - { - /* When j=10, j^i will have i+1 digits (e.g if i=3, 10^3=1000).*/ - for(j = 1; j < 10; j++) - { - mpz_ui_pow_ui(p, j, i); + while(!finished) + { + /* When j=10, j^i will have i+1 digits (e.g if i=3, 10^3=1000).*/ + for(j = 1; j < 10; j++) + { + mpz_ui_pow_ui(p, j, i); - if(count_digits(p) == i) - { - count++; - } - } + if(count_digits(p) == i) + { + count++; + } + } - /* When 9^i has less than i digits, all the numbers have been found.*/ - if(count_digits(p) < i) - { - finished = 1; - } + /* When 9^i has less than i digits, all the numbers have been found.*/ + if(count_digits(p) < i) + { + 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("Answer: %d\n", count); - - printf("Elapsed time: %.9lf seconds\n", elapsed); + printf("Project Euler, Problem 63\n"); + printf("Answer: %d\n", count); - return 0; + printf("Elapsed time: %.9lf seconds\n", elapsed); + + return 0; } int count_digits(mpz_t n) { - int count = 0; - mpz_t tmp; + int count = 0; + mpz_t tmp; - if(mpz_cmp_ui(n, 0) == 0) - { - return 1; - } + if(mpz_cmp_ui(n, 0) == 0) + { + return 1; + } - mpz_init_set(tmp, n); + mpz_init_set(tmp, n); - while(mpz_cmp_ui(tmp, 0)) - { - mpz_tdiv_q_ui(tmp, tmp, 10); - count++; - } + while(mpz_cmp_ui(tmp, 0)) + { + mpz_tdiv_q_ui(tmp, tmp, 10); + count++; + } - return count; + return count; } diff --git a/C/p064.c b/C/p064.c index e23fdc1..1d37f5f 100644 --- a/C/p064.c +++ b/C/p064.c @@ -40,6 +40,8 @@ * * How many continued fractions for N≤10000 have an odd period?*/ +#define _POSIX_C_SOURCE 199309L + #include #include #include @@ -50,60 +52,60 @@ int is_square(int n); int main(int argc, char **argv) { - int i, count = 0, period; - int *fraction; - double elapsed; - struct timespec start, end; + int i, count = 0, period; + int *fraction; + double elapsed; + struct timespec start, end; - clock_gettime(CLOCK_MONOTONIC, &start); + clock_gettime(CLOCK_MONOTONIC, &start); - for(i = 2; i <= 10000; i++) - { - /* Perfect squares are obviously not represented as continued fractions. - * For all other numbers, calculate their period and check if it's odd.*/ - if(!is_square(i)) - { - if((fraction = build_sqrt_cont_fraction(i, &period, 300)) == NULL) - { - fprintf(stderr, "Error! Build_cont_fraction function returned NULL\n"); - return 1; - } + for(i = 2; i <= 10000; i++) + { + /* Perfect squares are obviously not represented as continued fractions. + * For all other numbers, calculate their period and check if it's odd.*/ + if(!is_square(i)) + { + if((fraction = build_sqrt_cont_fraction(i, &period, 300)) == NULL) + { + fprintf(stderr, "Error! Build_cont_fraction function returned NULL\n"); + return 1; + } - if(period % 2 != 0) - { - count++; - } - } - } + if(period % 2 != 0) + { + 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("Answer: %d\n", count); + printf("Project Euler, Problem 64\n"); + 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 m; - double p; + int m; + double p; - p = sqrt(n); - m = p; + p = sqrt(n); + m = p; - if(p == m) - { - return 1; - } - else - { - return 0; - } + if(p == m) + { + return 1; + } + else + { + return 0; + } } diff --git a/C/p065.c b/C/p065.c index 9c6cf20..418b75a 100644 --- a/C/p065.c +++ b/C/p065.c @@ -27,6 +27,8 @@ * * Find the sum of digits in the numerator of the 100th convergent of the continued fraction for e.*/ +#define _POSIX_C_SOURCE 199309L + #include #include #include @@ -34,55 +36,55 @@ int main(int argc, char **argv) { - int i, ai[3] = {1, 2, 1}, count = 4, sum = 0; - mpz_t n0, n1, n2; - double elapsed; - struct timespec start, end; + int i, ai[3] = {1, 2, 1}, count = 4, sum = 0; + mpz_t n0, n1, n2; + double elapsed; + struct timespec start, end; - clock_gettime(CLOCK_MONOTONIC, &start); + clock_gettime(CLOCK_MONOTONIC, &start); - mpz_init_set_ui(n0, 3); - mpz_init_set_ui(n1, 8); - mpz_init_set_ui(n2, 11); + mpz_init_set_ui(n0, 3); + mpz_init_set_ui(n1, 8); + mpz_init_set_ui(n2, 11); - /* 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 - * 3, 8 and 11, the next ones are easily calculated, considering that a_n - * follows a simple pattern: - * a_1=1, a_2=2, a_3=1 - * a_4=1, a_5=4, a_6=1 - * a_7=1, a_8=6, a_9=1 - * and so on.*/ - while(count < 100) - { - ai[1] += 2; + /* 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 + * 3, 8 and 11, the next ones are easily calculated, considering that a_n + * follows a simple pattern: + * a_1=1, a_2=2, a_3=1 + * a_4=1, a_5=4, a_6=1 + * a_7=1, a_8=6, a_9=1 + * and so on.*/ + while(count < 100) + { + ai[1] += 2; - for(i = 0; i < 3 && count < 100; i++) - { - mpz_set(n0, n1); - mpz_set(n1, n2); - mpz_mul_ui(n2, n1, ai[i]); - mpz_add(n2, n2, n0); - count++; - } - } + for(i = 0; i < 3 && count < 100; i++) + { + mpz_set(n0, n1); + mpz_set(n1, n2); + mpz_mul_ui(n2, n1, ai[i]); + mpz_add(n2, n2, n0); + count++; + } + } - /* Sum the digits.*/ - while(mpz_cmp_ui(n2, 0)) - { - sum += mpz_tdiv_q_ui(n2, n2, 10); - } + /* Sum the digits.*/ + while(mpz_cmp_ui(n2, 0)) + { + 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("Answer: %d\n", sum); + printf("Project Euler, Problem 65\n"); + printf("Answer: %d\n", sum); - printf("Elapsed time: %.9lf seconds\n", elapsed); + printf("Elapsed time: %.9lf seconds\n", elapsed); - return 0; + return 0; } diff --git a/C/p066.c b/C/p066.c index 3d42f2d..2d75e4a 100644 --- a/C/p066.c +++ b/C/p066.c @@ -18,6 +18,8 @@ * * 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 #include #include @@ -29,64 +31,63 @@ int is_square(int n); int main(int argc, char **argv) { - int i, max_d = -1; - mpz_t x, max; - double elapsed; - struct timespec start, end; - - clock_gettime(CLOCK_MONOTONIC, &start); + int i, max_d = -1; + mpz_t x, max; + double elapsed; + struct timespec start, end; + + clock_gettime(CLOCK_MONOTONIC, &start); // mpz_init(x); - mpz_init_set_ui(max, 0); + mpz_init_set_ui(max, 0); - for(i = 2; i <= 1000; i++) - { - if(!is_square(i)) - { - /* Solve the Diophantine equation x^2-D*y^2=1 (Pell equation)*/ - if(pell_eq(i, x) == -1) - { - fprintf(stderr, "Error! Pell_eq function failed\n"); - return 1; - } - - if(mpz_cmp(x, max) > 0) - { - mpz_set(max, x); - max_d = i; - } - } - } + for(i = 2; i <= 1000; i++) + { + if(!is_square(i)) + { + /* Solve the Diophantine equation x^2-D*y^2=1 (Pell equation)*/ + if(pell_eq(i, x) == -1) + { + fprintf(stderr, "Error! Pell_eq function failed\n"); + return 1; + } - mpz_clears(x, max, NULL); - - clock_gettime(CLOCK_MONOTONIC, &end); + if(mpz_cmp(x, max) > 0) + { + mpz_set(max, x); + max_d = i; + } + } + } - elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; + mpz_clears(x, max, NULL); - printf("Project Euler, Problem 66\n"); - printf("Answer: %d\n", max_d); + 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 66\n"); + printf("Answer: %d\n", max_d); + + printf("Elapsed time: %.9lf seconds\n", elapsed); + + return 0; } int is_square(int n) { - int m; - double p; + int m; + double p; - p = sqrt(n); - m = p; + p = sqrt(n); + m = p; - if(p == m) - { - return 1; - } - else - { - return 0; - } + if(p == m) + { + return 1; + } + else + { + return 0; + } } - diff --git a/C/p067.c b/C/p067.c index cc07110..85f0be9 100644 --- a/C/p067.c +++ b/C/p067.c @@ -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. * There is an efficient algorithm to solve it. ;o)*/ +#define _POSIX_C_SOURCE 199309L + #include #include #include @@ -20,63 +22,63 @@ int main(int argc, char **argv) { - int i, j, max; - int **triang; - double elapsed; - FILE *fp; - struct timespec start, end; + int i, j, max; + int **triang; + double elapsed; + FILE *fp; + struct timespec start, end; - clock_gettime(CLOCK_MONOTONIC, &start); + clock_gettime(CLOCK_MONOTONIC, &start); - if((triang = (int **)malloc(100*sizeof(int *))) == NULL) - { - fprintf(stderr, "Error while allocating memory\n"); - return 1; - } + if((triang = (int **)malloc(100*sizeof(int *))) == NULL) + { + fprintf(stderr, "Error while allocating memory\n"); + return 1; + } - for(i = 1; i <= 100; i++) - { - if((triang[i-1] = (int *)malloc(i*sizeof(int))) == NULL) - { - fprintf(stderr, "Error while allocating memory\n"); - return 1; - } - } + for(i = 1; i <= 100; i++) + { + if((triang[i-1] = (int *)malloc(i*sizeof(int))) == NULL) + { + fprintf(stderr, "Error while allocating memory\n"); + return 1; + } + } - if((fp = fopen("triangle.txt", "r")) == NULL) - { - fprintf(stderr, "Error while opening file %s\n", "triangle.txt"); - return 1; - } + if((fp = fopen("triangle.txt", "r")) == NULL) + { + fprintf(stderr, "Error while opening file %s\n", "triangle.txt"); + return 1; + } - for(i = 1; i <= 100; i++) - { - for(j = 0; j < i; j++) - { - fscanf(fp, "%d", &triang[i-1][j]); - } - } + for(i = 1; i <= 100; i++) + { + for(j = 0; j < i; j++) + { + fscanf(fp, "%d", &triang[i-1][j]); + } + } - fclose(fp); + fclose(fp); - /* Use the function implemented in projecteuler.c to find the maximum path.*/ - max = find_max_path(triang, 100); + /* Use the function implemented in projecteuler.c to find the maximum path.*/ + max = find_max_path(triang, 100); - for(i = 0; i < 100; i++) - { - free(triang[i]); - } + for(i = 0; i < 100; 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("Answer: %d\n", max); + printf("Project Euler, Problem 67\n"); + printf("Answer: %d\n", max); - printf("Elapsed time: %.9lf seconds\n", elapsed); + printf("Elapsed time: %.9lf seconds\n", elapsed); - return 0; + return 0; } diff --git a/C/p068.c b/C/p068.c index 4c538ce..ee45c00 100644 --- a/C/p068.c +++ b/C/p068.c @@ -43,6 +43,8 @@ * O */ +#define _POSIX_C_SOURCE 199309L + #include #include #include @@ -56,79 +58,79 @@ int compare(void *a, void *b); int main(int argc, char **argv) { - int i; - int *eval, **ring; - long int n, max = 0; - double elapsed; - struct timespec start, end; + int i; + int *eval, **ring; + long int n, max = 0; + double elapsed; + struct timespec start, end; - clock_gettime(CLOCK_MONOTONIC, &start); + clock_gettime(CLOCK_MONOTONIC, &start); - if((ring = (int **)malloc(10*sizeof(int *))) == NULL) - { - fprintf(stderr, "Error while allocating memory\n"); - return 1; - } + if((ring = (int **)malloc(10*sizeof(int *))) == NULL) + { + fprintf(stderr, "Error while allocating memory\n"); + return 1; + } - for(i = 0; i < 10; i++) - { - if((ring[i] = (int *)malloc(sizeof(int))) == NULL) - { - fprintf(stderr, "Error while allocating memory\n"); - return 1; - } - *ring[i] = i + 1; - } + for(i = 0; i < 10; i++) + { + if((ring[i] = (int *)malloc(sizeof(int))) == NULL) + { + fprintf(stderr, "Error while allocating memory\n"); + return 1; + } + *ring[i] = i + 1; + } - /* Check if the first permutation of values is a possible solution.*/ - eval = eval_ring(ring, 5); + /* Check if the first permutation of values is a possible solution.*/ + eval = eval_ring(ring, 5); - /* Convert the vector into an integer number.*/ - n = array_to_long(eval, 15); + /* Convert the vector into an integer number.*/ + n = array_to_long(eval, 15); - if(n > max) - { - max = n; - } - - free(eval); + if(n > max) + { + max = n; + } - /* Generate all possible permutations, for each one check if - * it's a possible solution for the ring and save the maximum.*/ - while(next_permutation((void **)ring, 10, compare) != -1) - { - eval = eval_ring(ring, 5); + free(eval); - n = array_to_long(eval, 15); + /* Generate all possible permutations, for each one check if + * it's a possible solution for the ring and save the maximum.*/ + while(next_permutation((void **)ring, 10, compare) != -1) + { + eval = eval_ring(ring, 5); - if(n > max) - { - max = n; - } - - free(eval); - } + n = array_to_long(eval, 15); - clock_gettime(CLOCK_MONOTONIC, &end); + if(n > max) + { + max = n; + } - elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; + free(eval); + } - printf("Project Euler, Problem 68\n"); - printf("Answer: %ld\n", max); + 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 68\n"); + printf("Answer: %ld\n", max); + + printf("Elapsed time: %.9lf seconds\n", elapsed); + + return 0; } int compare(void *a, void *b) { - int *n1, *n2; + int *n1, *n2; - n1 = (int *)a; - n2 = (int *)b; + n1 = (int *)a; + 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, @@ -136,82 +138,82 @@ int compare(void *a, void *b) * represent the internal ring.*/ int *eval_ring(int **ring, int n) { - int i, j, magic_val, val; - int *res; + int i, j, magic_val, val; + int *res; - for(i = 1; i < n; i++) - { - /* We need to start from the lowest external node, so if - * the first element in the vector is not the lowest of - * the first n elements (the external elements), the configuration - * is not a valid one.*/ - if(*ring[i] < *ring[0]) - { - return NULL; - } - } - - if((res = (int *)malloc(3*n*sizeof(int))) == NULL) - { - fprintf(stderr, "Error while allocating memory\n"); - return NULL; - } + for(i = 1; i < n; i++) + { + /* We need to start from the lowest external node, so if + * the first element in the vector is not the lowest of + * the first n elements (the external elements), the configuration + * is not a valid one.*/ + if(*ring[i] < *ring[0]) + { + return NULL; + } + } - /* Each group of three must have the same value.*/ - magic_val = *ring[0] + *ring[n] + *ring[n+1]; + if((res = (int *)malloc(3*n*sizeof(int))) == NULL) + { + fprintf(stderr, "Error while allocating memory\n"); + return NULL; + } - for(i = 0, j = 0; i < n; i++, j += 3) - { - /* We need to find the maximum 16-digit string, this is - * possible only if the element "10" is used only once, - * i.e. if it's one of the external nodes.*/ - if(*ring[n+i] == 10 || *ring[n+(i+1)%n] == 10) - { - return NULL; - } + /* Each group of three must have the same value.*/ + magic_val = *ring[0] + *ring[n] + *ring[n+1]; - /* Check that the value of the current three-element group - * is the "magic" value.*/ - val = *ring[i] + *ring[n+i] + *ring[n+(i+1)%n]; + for(i = 0, j = 0; i < n; i++, j += 3) + { + /* We need to find the maximum 16-digit string, this is + * possible only if the element "10" is used only once, + * i.e. if it's one of the external nodes.*/ + if(*ring[n+i] == 10 || *ring[n+(i+1)%n] == 10) + { + return NULL; + } - if(val != magic_val) - { - return NULL; - } + /* Check that the value of the current three-element group + * is the "magic" value.*/ + val = *ring[i] + *ring[n+i] + *ring[n+(i+1)%n]; - /* Save the current element group in the result string.*/ - res[j] = *ring[i]; - res[j+1] = *ring[n+i]; - res[j+2] = *ring[n+(i+1)%n]; - } + if(val != magic_val) + { + return NULL; + } - return res; + /* Save the current element group in the result string.*/ + res[j] = *ring[i]; + res[j+1] = *ring[n+i]; + res[j+2] = *ring[n+(i+1)%n]; + } + + return res; } /* Function to convert the vector into a long int.*/ long int array_to_long(int *n, int len) { - int i, k = 0; - long int res = 0; + int i, k = 0; + long int res = 0; - if(n == NULL) - { - return 0; - } + if(n == NULL) + { + return 0; + } - for(i = len - 1; i >= 0; i--) - { - res += n[i] * pow(10, k); + for(i = len - 1; i >= 0; i--) + { + res += n[i] * pow(10, k); - if(n[i] >= 10) - { - k += 2; - } - else - { - k++; - } - } + if(n[i] >= 10) + { + k += 2; + } + else + { + k++; + } + } - return res; + return res; } diff --git a/C/p069.c b/C/p069.c index 8f201e5..96c2c97 100644 --- a/C/p069.c +++ b/C/p069.c @@ -16,6 +16,8 @@ * * Find the value of n ≤ 1,000,000 for which n/φ(n) is a maximum.*/ +#define _POSIX_C_SOURCE 199309L + #include #include #include @@ -27,7 +29,7 @@ int main(int argc, char **argv) { int i, res = 1; - double elapsed; + double elapsed; struct timespec start, end; clock_gettime(CLOCK_MONOTONIC, &start); @@ -43,7 +45,7 @@ int main(int argc, char **argv) while(res < N) { i++; - + if(is_prime(i)) { res *= i; @@ -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; printf("Project Euler, Problem 69\n"); - printf("Answer: %d\n", res); + printf("Answer: %d\n", res); printf("Elapsed time: %.9lf seconds\n", elapsed); - return 0; + return 0; } diff --git a/C/p070.c b/C/p070.c index beae7e5..1d8aeab 100644 --- a/C/p070.c +++ b/C/p070.c @@ -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.*/ +#define _POSIX_C_SOURCE 199309L + #include #include #include @@ -20,78 +22,78 @@ int is_permutation(int a, int b); int main(int argc, char **argv) { - int i, a, b, p, n = -1; - int *primes; - double elapsed, min = DBL_MAX; - struct timespec start, end; + int i, a, b, p, n = -1; + int *primes; + double elapsed, min = DBL_MAX; + struct timespec start, end; - clock_gettime(CLOCK_MONOTONIC, &start); + clock_gettime(CLOCK_MONOTONIC, &start); - if((primes = sieve(N)) == NULL) - { - fprintf(stderr, "Error! Sieve function returned NULL\n"); - return 1; - } + if((primes = sieve(N)) == NULL) + { + fprintf(stderr, "Error! Sieve function returned NULL\n"); + return 1; + } - for(i = 2; i < N; i++) - { - /* 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 - * 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 - * check if phi(n) is a permutation of n and update the minimum if it's - * smaller.*/ - if(is_semiprime(i, &a, &b, primes)) - { - p = phi_semiprime(i, a, b); + for(i = 2; i < N; i++) + { + /* 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 + * 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 + * check if phi(n) is a permutation of n and update the minimum if it's + * smaller.*/ + if(is_semiprime(i, &a, &b, primes)) + { + p = phi_semiprime(i, a, b); - if(is_permutation(p, i) && (double)i / p < min) - { - n = i; - min = (double)i / p; - } - } - } + if(is_permutation(p, i) && (double)i / p < min) + { + n = i; + 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("Answer: %d\n", n); + printf("Project Euler, Problem 70\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 i; - int digits1[10] = {0}, digits2[10] = {0}; + int i; + int digits1[10] = {0}, digits2[10] = {0}; - /* Get digits of a.*/ - while(a > 0) - { - digits1[a%10]++; - a /= 10; - } + /* Get digits of a.*/ + while(a > 0) + { + digits1[a%10]++; + a /= 10; + } - /* Get digits of b.*/ - while(b > 0) - { - digits2[b%10]++; - b /= 10; - } + /* Get digits of b.*/ + while(b > 0) + { + digits2[b%10]++; + b /= 10; + } - /* If they're not the same, return 0.*/ - for(i = 0; i < 10; i++) - { - if(digits1[i] != digits2[i]) - { - return 0; - } - } + /* If they're not the same, return 0.*/ + for(i = 0; i < 10; i++) + { + if(digits1[i] != digits2[i]) + { + return 0; + } + } - return 1; + return 1; } diff --git a/C/p071.c b/C/p071.c index 48bf01b..b50350c 100644 --- a/C/p071.c +++ b/C/p071.c @@ -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 * of the fraction immediately to the left of 3/7.*/ +#define _POSIX_C_SOURCE 199309L + #include #include #include @@ -18,47 +20,47 @@ int main(int argc, char **argv) { - int i, j, n, d, max_n; - double elapsed, max = 0.0; - struct timespec start, end; + int i, j, n, d, max_n; + double elapsed, max = 0.0; + 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 - * p/q max) - { - n = j; - d = i; - max = (double)n / d; + if((double)j / i > max) + { + n = j; + d = i; + max = (double)n / d; - /* Reduce the fraction if it's not already reduced.*/ - if(gcd(i, j) > 1) - { - n /= gcd(i, j); - d /= gcd(i, j); - } + /* Reduce the fraction if it's not already reduced.*/ + if(gcd(i, j) > 1) + { + n /= 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("Answer: %d\n", max_n); + printf("Project Euler, Problem 71\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; } diff --git a/C/p072.c b/C/p072.c index c3da000..951bef4 100644 --- a/C/p072.c +++ b/C/p072.c @@ -8,6 +8,8 @@ * * How many elements would be contained in the set of reduced proper fractions for d ≤ 1,000,000?*/ +#define _POSIX_C_SOURCE 199309L + #include #include #include @@ -18,37 +20,37 @@ int main(int argc, char **argv) { - int i; - int *primes; - long int count = 0; - double elapsed; - struct timespec start, end; + int i; + int *primes; + long int count = 0; + double elapsed; + struct timespec start, end; - clock_gettime(CLOCK_MONOTONIC, &start); + clock_gettime(CLOCK_MONOTONIC, &start); - if((primes = sieve(N)) == NULL) - { - fprintf(stderr, "Error! Sieve function returned NULL\n"); - return 1; - } + if((primes = sieve(N)) == NULL) + { + fprintf(stderr, "Error! Sieve function returned NULL\n"); + return 1; + } - /* 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 - * of Euler's Totient Function phi. It's sufficient to calculate phi for each - * denominator and sum the value.*/ - for(i = 2; i < N; i++) - { - count += phi(i, primes); - } - - clock_gettime(CLOCK_MONOTONIC, &end); + /* 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 + * of Euler's Totient Function phi. It's sufficient to calculate phi for each + * denominator and sum the value.*/ + for(i = 2; i < N; i++) + { + count += phi(i, primes); + } - elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; + clock_gettime(CLOCK_MONOTONIC, &end); - printf("Project Euler, Problem 72\n"); - printf("Answer: %ld\n", count); + elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; - printf("Elapsed time: %.9lf seconds\n", elapsed); + printf("Project Euler, Problem 72\n"); + printf("Answer: %ld\n", count); - return 0; + printf("Elapsed time: %.9lf seconds\n", elapsed); + + return 0; } diff --git a/C/p073.c b/C/p073.c index 82821fb..7ea7b07 100644 --- a/C/p073.c +++ b/C/p073.c @@ -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?*/ +#define _POSIX_C_SOURCE 199309L + #include #include #include @@ -15,37 +17,37 @@ int main(int argc, char **argv) { - int i, j, limit, count = 0; - double elapsed; - struct timespec start, end; + int i, j, limit, count = 0; + double elapsed; + 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 - * 1/3

#include #include @@ -34,99 +36,99 @@ int chains[N] = {0}; int main(int argc, char **argv) { - int i, count = 0; - double elapsed; - struct timespec start, end; + int i, count = 0; + double elapsed; + struct timespec start, end; - clock_gettime(CLOCK_MONOTONIC, &start); + clock_gettime(CLOCK_MONOTONIC, &start); - /* Simple brute force approach, for every number calculate - * the length of the chain.*/ - for(i = 3; i < N; i++) - { - if(len_chain(i) == 60) - { - count++; - } - } - - clock_gettime(CLOCK_MONOTONIC, &end); + /* Simple brute force approach, for every number calculate + * the length of the chain.*/ + for(i = 3; i < N; i++) + { + if(len_chain(i) == 60) + { + count++; + } + } - elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; + clock_gettime(CLOCK_MONOTONIC, &end); - printf("Project Euler, Problem 74\n"); - printf("Answer: %d\n", count); + elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; - printf("Elapsed time: %.9lf seconds\n", elapsed); + printf("Project Euler, Problem 74\n"); + printf("Answer: %d\n", count); - return 0; + printf("Elapsed time: %.9lf seconds\n", elapsed); + + return 0; } /* Recursively calculate the factorial, of a number, saving the result * so that it can be reused later.*/ int factorial(int n) { - if(n == 0 || n == 1) - { - return 1; - } - else if(factorials[n] != 0) - { - return factorials[n]; - } - else - { - factorials[n]=n*factorial(n-1); - return factorials[n]; - } + if(n == 0 || n == 1) + { + return 1; + } + else if(factorials[n] != 0) + { + return factorials[n]; + } + else + { + factorials[n]=n*factorial(n-1); + return factorials[n]; + } } int len_chain(int n) { - int i, count = 0, finished = 0, value, tmp; - int chain[60]; + int i, count = 0, finished = 0, value, tmp; + int chain[60]; - value = n; - chain[count] = value; + value = n; + chain[count] = value; - while(!finished) - { - tmp = 0; - count++; + while(!finished) + { + tmp = 0; + count++; - /* Generate the next number of the chain by taking - * the digits of the current value, calculating the - * factorials and adding them.*/ - while(value != 0) - { - tmp += factorial(value % 10); - value /= 10; - } + /* Generate the next number of the chain by taking + * the digits of the current value, calculating the + * factorials and adding them.*/ + while(value != 0) + { + tmp += factorial(value % 10); + value /= 10; + } - /* If the chain length for the new value has already been - * calculated before, use the saved value (only chains for - * values smaller than N are saved).*/ - if(tmp < N && chains[tmp] != 0) - { - return count + chains[tmp]; - } + /* If the chain length for the new value has already been + * calculated before, use the saved value (only chains for + * values smaller than N are saved).*/ + if(tmp < N && chains[tmp] != 0) + { + return count + chains[tmp]; + } - value = tmp; + value = tmp; - /* If the current value is already present in the chain, - * the chain is finished.*/ - for(i = 0; i < count; i++) - { - if(chain[i] == value) - { - finished = 1; - } - } + /* If the current value is already present in the chain, + * the chain is finished.*/ + for(i = 0; i < count; i++) + { + if(chain[i] == value) + { + finished = 1; + } + } - chain[count] = value; - } + chain[count] = value; + } - chains[n] = count; + chains[n] = count; - return count; + return count; } diff --git a/C/p075.c b/C/p075.c index ce467f3..551ab9e 100644 --- a/C/p075.c +++ b/C/p075.c @@ -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?*/ +#define _POSIX_C_SOURCE 199309L + #include #include #include @@ -24,79 +26,79 @@ int main(int argc, char **argv) { - int i, a, b, c, tmpa, tmpb, tmpc, m, n, count = 0; - int *l; - double elapsed; - struct timespec start, end; + int i, a, b, c, tmpa, tmpb, tmpc, m, n, count = 0; + int *l; + double elapsed; + struct timespec start, end; - clock_gettime(CLOCK_MONOTONIC, &start); + clock_gettime(CLOCK_MONOTONIC, &start); - if((l = (int *)calloc(N + 1, sizeof(int))) == NULL) - { - fprintf(stderr, "Error while allocating memory\n"); - return 1; - } + if((l = (int *)calloc(N + 1, sizeof(int))) == NULL) + { + fprintf(stderr, "Error while allocating memory\n"); + return 1; + } - /* Generate all Pythagorean triplets using Euclid's algorithm: - * For m>=2 and n=2 and n #include #include @@ -16,34 +18,34 @@ int main(int argc, char **argv) { - int n; - long int *partitions; - double elapsed; - struct timespec start, end; + int n; + long int *partitions; + double elapsed; + struct timespec start, end; - clock_gettime(CLOCK_MONOTONIC, &start); + clock_gettime(CLOCK_MONOTONIC, &start); - if((partitions = (long int *)calloc(100, sizeof(long int))) == NULL) - { - fprintf(stderr, "Error while allocating memory\n"); - return 1; - } + if((partitions = (long int *)calloc(100, sizeof(long int))) == NULL) + { + fprintf(stderr, "Error while allocating memory\n"); + return 1; + } - /* 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). - * The function is implemented in projecteuler.c*/ - n = partition_fn(100, partitions, -1) - 1; + /* 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). + * The function is implemented in projecteuler.c*/ + 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("Answer: %d\n", n); + printf("Project Euler, Problem 76\n"); + printf("Answer: %d\n", n); - printf("Elapsed time: %.9lf seconds\n", elapsed); + printf("Elapsed time: %.9lf seconds\n", elapsed); - return 0; + return 0; } diff --git a/C/p077.c b/C/p077.c index b5740ce..4b50c58 100644 --- a/C/p077.c +++ b/C/p077.c @@ -8,6 +8,8 @@ * * 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 #include #include @@ -15,69 +17,69 @@ #include "projecteuler.h" int count(int value, int n, int i, int target); - + int primes[100]; int main(int argc, char **argv) { - int i, j, n; - double elapsed; - struct timespec start, end; + int i, j, n; + double elapsed; + struct timespec start, end; - clock_gettime(CLOCK_MONOTONIC, &start); + clock_gettime(CLOCK_MONOTONIC, &start); - /* Generate a list of the first 100 primes.*/ - for(i = 0, j = 0; j < 100; i++) - { - if(is_prime(i)) - { - primes[j++] = i; - } - } + /* Generate a list of the first 100 primes.*/ + for(i = 0, j = 0; j < 100; i++) + { + if(is_prime(i)) + { + primes[j++] = i; + } + } - i = 1; + i = 1; - /* Use a function to count the number of prime partitions for - * each number >= 2 until the one that can be written in over - * 5000 ways is found.*/ - while((n = count(0, 0, 0, ++i)) <= 5000); + /* Use a function to count the number of prime partitions for + * each number >= 2 until the one that can be written in over + * 5000 ways is found.*/ + 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("Answer: %d\n", i); + printf("Project Euler, Problem 77\n"); + 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 * to find all the partitions.*/ int count(int value, int n, int i, int target) { - int j; + int j; - for(j = i; j < 100; j++) - { - value += primes[j]; + for(j = i; j < 100; j++) + { + value += primes[j]; - if(value == target) - { - return n + 1; - } - else if(value > target) - { - return n; - } - else - { - n = count(value, n, j, target); - value -= primes[j]; - } - } + if(value == target) + { + return n + 1; + } + else if(value > target) + { + return n; + } + else + { + n = count(value, n, j, target); + value -= primes[j]; + } + } - return n; + return n; } diff --git a/C/p078.c b/C/p078.c index c7c7a3d..236650b 100644 --- a/C/p078.c +++ b/C/p078.c @@ -11,6 +11,8 @@ * * Find the least value of n for which p(n) is divisible by one million.*/ +#define _POSIX_C_SOURCE 199309L + #include #include #include @@ -20,25 +22,25 @@ int main(int argc, char **argv) { - int i = -1; - long int partitions[N] = {0}; - double elapsed; - struct timespec start, end; + int i = -1; + long int partitions[N] = {0}; + double elapsed; + struct timespec start, end; - clock_gettime(CLOCK_MONOTONIC, &start); + clock_gettime(CLOCK_MONOTONIC, &start); - /* Using the partition function to calculate the number of partitions, - * giving the result modulo N.*/ - while(partition_fn(++i, partitions, N) != 0); - - clock_gettime(CLOCK_MONOTONIC, &end); + /* Using the partition function to calculate the number of partitions, + * giving the result modulo N.*/ + while(partition_fn(++i, partitions, N) != 0); - elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; + clock_gettime(CLOCK_MONOTONIC, &end); - printf("Project Euler, Problem 78\n"); - printf("Answer: %d\n", i); + elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; - printf("Elapsed time: %.9lf seconds\n", elapsed); + printf("Project Euler, Problem 78\n"); + printf("Answer: %d\n", i); - return 0; + printf("Elapsed time: %.9lf seconds\n", elapsed); + + return 0; } diff --git a/C/p079.c b/C/p079.c index 78e6756..238a3fb 100644 --- a/C/p079.c +++ b/C/p079.c @@ -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 * secret passcode of unknown length.*/ +#define _POSIX_C_SOURCE 199309L + #include #include #include @@ -16,174 +18,174 @@ int check_passcode(int **passcode, int len, int **logins, int n); int main(int argc, char **argv) { - int i, j, keylog, len = 4, found = 0, digits[10] = {0}, passcode_digits[10] = {0}, **passcode, **logins; - char line[5]; - FILE *fp; - double elapsed; - struct timespec start, end; + int i, j, keylog, len = 4, found = 0, digits[10] = {0}, passcode_digits[10] = {0}, **passcode, **logins; + char line[5]; + FILE *fp; + double elapsed; + struct timespec start, end; - clock_gettime(CLOCK_MONOTONIC, &start); + clock_gettime(CLOCK_MONOTONIC, &start); - if((fp = fopen("keylog.txt", "r")) == NULL) - { - fprintf(stderr, "Error while opening file %s\n", "keylog.txt"); - return 1; - } + if((fp = fopen("keylog.txt", "r")) == NULL) + { + fprintf(stderr, "Error while opening file %s\n", "keylog.txt"); + return 1; + } - if((logins = (int **)malloc(50*sizeof(int*))) == NULL) - { - fprintf(stderr, "Error while allocating memory\n"); - return 1; - } + if((logins = (int **)malloc(50*sizeof(int*))) == NULL) + { + fprintf(stderr, "Error while allocating memory\n"); + return 1; + } - for(i = 0; i < 50; i++) - { - 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) - { + for(i = 0; i < 50; i++) + { + if((logins[i] = (int *)malloc(3*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; - break; - } + i = 0; - /* For the given length, check every permutation until the correct - * passcode has been found, or all the permutations have been tried.*/ - while(next_permutation((void **)passcode, len, compare) != -1) - { - 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(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"); + 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; break; - } - } + } - for(i = 0; i < len; i++) - { - free(passcode[i]); - } - free(passcode); + /* For the given length, check every permutation until the correct + * passcode has been found, or all the permutations have been tried.*/ + while(next_permutation((void **)passcode, len, compare) != -1) + { + 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.*/ - len++; - } + found = 1; + break; + } + } - for(i = 0; i < 50; i++) - { - free(logins[i]); - } + for(i = 0; i < len; i++) + { + free(passcode[i]); + } + free(passcode); - free(logins); - - clock_gettime(CLOCK_MONOTONIC, &end); + /* If the passcode has not yet been found, try a longer passcode.*/ + len++; + } - elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; + for(i = 0; i < 50; i++) + { + free(logins[i]); + } - printf("Elapsed time: %.9lf seconds\n", elapsed); + free(logins); - return 0; + clock_gettime(CLOCK_MONOTONIC, &end); + + 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 *n1, *n2; + int *n1, *n2; - n1 = (int *)a; - n2 = (int *)b; + n1 = (int *)a; + n2 = (int *)b; - return *n1 - *n2; + return *n1 - *n2; } 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 - * passcode in the correct order. Return 0 if a login attempt - * incompatible with the current passcode is found.*/ - for(i = 0; i < n; i++) - { - k = 0; - for(j = 0; j < len; j++) - { - if(*passcode[j] == logins[i][k]) - { - k++; - - if(k == 3) + /* For every login attempt, check if all the digits appear in the + * passcode in the correct order. Return 0 if a login attempt + * incompatible with the current passcode is found.*/ + for(i = 0; i < n; i++) + { + k = 0; + for(j = 0; j < len; j++) + { + if(*passcode[j] == logins[i][k]) { - break; + k++; + + if(k == 3) + { + break; + } } - } - } + } - if(k < 3) - { - return 0; - } - } + if(k < 3) + { + return 0; + } + } - return 1; + return 1; } diff --git a/C/p080.c b/C/p080.c index 1cad2e8..47667f7 100644 --- a/C/p080.c +++ b/C/p080.c @@ -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 all the irrational square roots*/ +#define _POSIX_C_SOURCE 199309L + #include #include #include @@ -16,65 +18,65 @@ int is_square(int n); int main(int argc, char **argv) { - int i, j, sum = 0; - char sqrt_digits[104]; - double elapsed; - struct timespec start, end; - mpf_t sqrt; + int i, j, sum = 0; + char sqrt_digits[104]; + double elapsed; + struct timespec start, end; + 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.*/ - mpf_set_default_prec(333); - mpf_init(sqrt); + /* Set the precision to 333 bits (should be enough for 100 decimal digits.*/ + mpf_set_default_prec(333); + mpf_init(sqrt); - for(i = 2; i < 100; i++) - { - if(is_square(i)) - { - continue; - } + for(i = 2; i < 100; i++) + { + if(is_square(i)) + { + continue; + } - /* Calculate the square root of the current number with the given precision - * and sum the digits to the total.*/ - mpf_sqrt_ui(sqrt, i); - gmp_sprintf(sqrt_digits, "%.101Ff\n", sqrt); - sum += (sqrt_digits[0] - '0'); + /* Calculate the square root of the current number with the given precision + * and sum the digits to the total.*/ + mpf_sqrt_ui(sqrt, i); + gmp_sprintf(sqrt_digits, "%.101Ff\n", sqrt); + sum += (sqrt_digits[0] - '0'); - for(j = 2; j < 101; j++) - { - sum += (sqrt_digits[j] - '0'); - } - } + for(j = 2; j < 101; j++) + { + sum += (sqrt_digits[j] - '0'); + } + } - mpf_clear(sqrt); - - clock_gettime(CLOCK_MONOTONIC, &end); + mpf_clear(sqrt); - elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; + clock_gettime(CLOCK_MONOTONIC, &end); - printf("Project Euler, Problem 80\n"); - printf("Answer: %d\n", sum); + elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; - printf("Elapsed time: %.9lf seconds\n", elapsed); + printf("Project Euler, Problem 80\n"); + printf("Answer: %d\n", sum); - return 0; + printf("Elapsed time: %.9lf seconds\n", elapsed); + + return 0; } int is_square(int n) { - int m; - double p; + int m; + double p; - p = sqrt(n); - m = p; + p = sqrt(n); + m = p; - if(p == m) - { - return 1; - } - else - { - return 0; - } + if(p == m) + { + return 1; + } + else + { + return 0; + } } diff --git a/C/p081.c b/C/p081.c index ebd2a65..73d8be2 100644 --- a/C/p081.c +++ b/C/p081.c @@ -1,6 +1,6 @@ /* In the 5 by 5 matrix below, the minimal path sum from the top left to the bottom right, by only moving to the right and down, * is indicated in bold red and is equal to 2427. - * + * * *131* 673 234 103 18 * *201* *96* *342* 965 150 * 630 803 *746* *422* 111 @@ -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 * by only moving right and down.*/ +#define _POSIX_C_SOURCE 199309L + #include #include #include @@ -19,92 +21,92 @@ int sum_paths(int **matrix, int m, int n); int main(int argc, char **argv) { - int i, j, dist; - int **matrix; - double elapsed; - struct timespec start, end; - FILE *fp; + int i, j, dist; + int **matrix; + double elapsed; + struct timespec start, end; + FILE *fp; - clock_gettime(CLOCK_MONOTONIC, &start); + clock_gettime(CLOCK_MONOTONIC, &start); - if((fp = fopen("matrix.txt", "r")) == NULL) - { - fprintf(stderr, "Error while opening file %s\n", "matrix.txt"); - return 1; - } + if((fp = fopen("matrix.txt", "r")) == NULL) + { + fprintf(stderr, "Error while opening file %s\n", "matrix.txt"); + return 1; + } - if((matrix = (int **)malloc(80*sizeof(int *))) == NULL) - { - fprintf(stderr, "Error while allocating memory\n"); - return 1; - } + if((matrix = (int **)malloc(80*sizeof(int *))) == NULL) + { + fprintf(stderr, "Error while allocating memory\n"); + return 1; + } - for(i = 0; i < 80; i++) - { - if((matrix[i] = (int *)malloc(80*sizeof(int))) == NULL) - { - fprintf(stderr, "Error while allocating memory\n"); - return 1; - } - } + for(i = 0; i < 80; i++) + { + if((matrix[i] = (int *)malloc(80*sizeof(int))) == NULL) + { + fprintf(stderr, "Error while allocating memory\n"); + return 1; + } + } - for(i = 0; i < 80; i++) - { - for(j = 0; j < 80; j++) - { - fscanf(fp, "%d,", &matrix[i][j]); - } - } + for(i = 0; i < 80; i++) + { + for(j = 0; j < 80; 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++) - { - free(matrix[i]); - } + for(i = 0; i < 80; i++) + { + free(matrix[i]); + } - free(matrix); - - clock_gettime(CLOCK_MONOTONIC, &end); + free(matrix); - elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; + clock_gettime(CLOCK_MONOTONIC, &end); - printf("Project Euler, Problem 81\n"); - printf("Answer: %d\n", dist); + elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; - printf("Elapsed time: %.9lf seconds\n", elapsed); + printf("Project Euler, Problem 81\n"); + printf("Answer: %d\n", dist); - return 0; + printf("Elapsed time: %.9lf seconds\n", elapsed); + + return 0; } /* Get the shortest path starting from the bottom right corner * and going backwards.*/ int sum_paths(int **matrix, int m, int n) { - int i, j; + int i, j; - for(i = m - 2; i >= 0; i--) - { - matrix[m-1][i] += matrix[m-1][i+1]; - matrix[i][m-1] += matrix[i+1][m-1]; - } + for(i = m - 2; i >= 0; i--) + { + matrix[m-1][i] += matrix[m-1][i+1]; + matrix[i][m-1] += matrix[i+1][m-1]; + } - for(i = m - 2; i >= 0; i--) - { - for(j = n - 2; j >= 0; j--) - { - if(matrix[i][j+1] > matrix[i+1][j]) - { - matrix[i][j] += matrix[i+1][j]; - } - else - { - matrix[i][j] += matrix[i][j+1]; - } - } - } + for(i = m - 2; i >= 0; i--) + { + for(j = n - 2; j >= 0; j--) + { + if(matrix[i][j+1] > matrix[i+1][j]) + { + matrix[i][j] += matrix[i+1][j]; + } + else + { + matrix[i][j] += matrix[i][j+1]; + } + } + } - return matrix[0][0]; + return matrix[0][0]; } diff --git a/C/p082.c b/C/p082.c index b3ac239..ddbb1af 100644 --- a/C/p082.c +++ b/C/p082.c @@ -7,10 +7,12 @@ * *201* *96* *342* 965 150 * 630 803 746 422 111 * 537 699 497 121 956 - * 805 732 524 37 331 + * 805 732 524 37 331 * * 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 #include #include @@ -19,85 +21,85 @@ int main(int argc, char **argv) { - int i, j, min_path=INT_MAX; - int **matrix, **distances; - double elapsed; - struct timespec start, end; - FILE *fp; + int i, j, min_path=INT_MAX; + int **matrix, **distances; + double elapsed; + struct timespec start, end; + FILE *fp; - clock_gettime(CLOCK_MONOTONIC, &start); - - if((fp = fopen("matrix.txt", "r")) == NULL) - { - fprintf(stderr, "Error while opening file %s\n", "matrix.txt"); - return 1; - } + clock_gettime(CLOCK_MONOTONIC, &start); - if((matrix = (int **)malloc(80*sizeof(int *))) == NULL || - (distances = (int **)malloc(80*sizeof(int *))) == NULL) - { - fprintf(stderr, "Error while allocating memory\n"); - return 1; - } + if((fp = fopen("matrix.txt", "r")) == NULL) + { + fprintf(stderr, "Error while opening file %s\n", "matrix.txt"); + return 1; + } - for(i = 0; i < 80; i++) - { - if((matrix[i] = (int *)malloc(80*sizeof(int))) == NULL || - (distances[i] = (int *)malloc(80*sizeof(int))) == NULL) - { - fprintf(stderr, "Error while allocating memory\n"); - return 1; - } - } + if((matrix = (int **)malloc(80*sizeof(int *))) == NULL || + (distances = (int **)malloc(80*sizeof(int *))) == NULL) + { + fprintf(stderr, "Error while allocating memory\n"); + return 1; + } - for(i = 0; i < 80; i++) - { - for(j = 0; j < 80; j++) - { - fscanf(fp, "%d,", &matrix[i][j]); - } - } + for(i = 0; i < 80; i++) + { + if((matrix[i] = (int *)malloc(80*sizeof(int))) == NULL || + (distances[i] = (int *)malloc(80*sizeof(int))) == NULL) + { + fprintf(stderr, "Error while allocating memory\n"); + return 1; + } + } - fclose(fp); + for(i = 0; i < 80; i++) + { + for(j = 0; j < 80; j++) + { + fscanf(fp, "%d,", &matrix[i][j]); + } + } - /* Use Dijkstra's algorithm starting from all possible nodes - * in the first column.*/ - for(i = 0; i < 80; i++) - { - if(dijkstra(matrix, distances, 80, 80, 1, 0, i) == -1) - { - fprintf(stderr, "Error! Dijkstra function returned -1\n"); - return 1; - } + fclose(fp); - /* For the current starting node, check if there is an ending node - * with a smaller path cost than the current minimum.*/ - for(j = 0; j < 80; j++) - { - if(distances[j][79] < min_path) - { - min_path = distances[j][79]; - } - } - } + /* Use Dijkstra's algorithm starting from all possible nodes + * in the first column.*/ + for(i = 0; i < 80; i++) + { + if(dijkstra(matrix, distances, 80, 80, 1, 0, i) == -1) + { + fprintf(stderr, "Error! Dijkstra function returned -1\n"); + return 1; + } - for(i = 0; i < 80; i++) - { - free(matrix[i]); - free(distances[i]); - } + /* For the current starting node, check if there is an ending node + * with a smaller path cost than the current minimum.*/ + for(j = 0; j < 80; j++) + { + if(distances[j][79] < min_path) + { + min_path = distances[j][79]; + } + } + } - free(matrix); - free(distances); - - clock_gettime(CLOCK_MONOTONIC, &end); + for(i = 0; i < 80; i++) + { + free(matrix[i]); + free(distances[i]); + } - elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; + free(matrix); + free(distances); - printf("Project Euler, Problem 82\n"); - printf("Answer: %d\n", min_path); + 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 82\n"); + printf("Answer: %d\n", min_path); + + printf("Elapsed time: %.9lf seconds\n", elapsed); + + return 0; } diff --git a/C/p083.c b/C/p083.c index 5ff3a0f..c967114 100644 --- a/C/p083.c +++ b/C/p083.c @@ -2,7 +2,7 @@ * * In the 5 by 5 matrix below, the minimal path sum from the top left to the bottom right, by moving left, right, up, and down, * is indicated in bold red and is equal to 2297. - * + * * *131* 673 *234* *103* *18* * *201* *96* *342* 965 *150* * 630 803 746 *422* *111* @@ -12,6 +12,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 by moving left, right, up, and down.*/ +#define _POSIX_C_SOURCE 199309L + #include #include #include @@ -20,73 +22,73 @@ int main(int argc, char **argv) { - int i, j, dist; - int **matrix, **distances; - double elapsed; - struct timespec start, end; - FILE *fp; + int i, j, dist; + int **matrix, **distances; + double elapsed; + struct timespec start, end; + FILE *fp; - clock_gettime(CLOCK_MONOTONIC, &start); + clock_gettime(CLOCK_MONOTONIC, &start); - if((fp = fopen("matrix.txt", "r")) == NULL) - { - fprintf(stderr, "Error while opening file %s\n", "matrix.txt"); - return 1; - } + if((fp = fopen("matrix.txt", "r")) == NULL) + { + fprintf(stderr, "Error while opening file %s\n", "matrix.txt"); + return 1; + } - if((matrix = (int **)malloc(80*sizeof(int *))) == NULL || - (distances = (int **)malloc(80*sizeof(int *))) == NULL) - { - fprintf(stderr, "Error while allocating memory\n"); - return 1; - } + if((matrix = (int **)malloc(80*sizeof(int *))) == NULL || + (distances = (int **)malloc(80*sizeof(int *))) == NULL) + { + fprintf(stderr, "Error while allocating memory\n"); + return 1; + } - for(i = 0; i < 80; i++) - { - if((matrix[i] = (int *)malloc(80*sizeof(int))) == NULL || - (distances[i] = (int *)malloc(80*sizeof(int))) == NULL) - { - fprintf(stderr, "Error while allocating memory\n"); - return 1; - } - } + for(i = 0; i < 80; i++) + { + if((matrix[i] = (int *)malloc(80*sizeof(int))) == NULL || + (distances[i] = (int *)malloc(80*sizeof(int))) == NULL) + { + fprintf(stderr, "Error while allocating memory\n"); + return 1; + } + } - for(i = 0; i < 80; i++) - { - for(j = 0; j < 80; j++) - { - fscanf(fp, "%d,", &matrix[i][j]); - } - } + for(i = 0; i < 80; i++) + { + for(j = 0; j < 80; j++) + { + fscanf(fp, "%d,", &matrix[i][j]); + } + } - fclose(fp); + fclose(fp); - /* Use Dijkstra's algorithm to find the minimum path.*/ - if(dijkstra(matrix, distances, 80, 80, 1, 1, 0) == -1) - { - fprintf(stderr, "Error! Dijkstra function returned -1\n"); - return 1; - } + /* Use Dijkstra's algorithm to find the minimum path.*/ + if(dijkstra(matrix, distances, 80, 80, 1, 1, 0) == -1) + { + fprintf(stderr, "Error! Dijkstra function returned -1\n"); + return 1; + } - dist = distances[79][79]; + dist = distances[79][79]; - for(i = 0; i < 80; i++) - { - free(matrix[i]); - free(distances[i]); - } + for(i = 0; i < 80; i++) + { + free(matrix[i]); + free(distances[i]); + } - free(matrix); - free(distances); - - clock_gettime(CLOCK_MONOTONIC, &end); + free(matrix); + free(distances); - elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; + clock_gettime(CLOCK_MONOTONIC, &end); - printf("Project Euler, Problem 83\n"); - printf("Answer: %d\n", dist); + elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; - printf("Elapsed time: %.9lf seconds\n", elapsed); + printf("Project Euler, Problem 83\n"); + printf("Answer: %d\n", dist); - return 0; + printf("Elapsed time: %.9lf seconds\n", elapsed); + + return 0; } diff --git a/C/p084.c b/C/p084.c index 929bb3d..3f1a815 100644 --- a/C/p084.c +++ b/C/p084.c @@ -52,7 +52,7 @@ * Go back 3 squares. * * The heart of this problem concerns the likelihood of visiting a particular square. That is, the probability of finishing - * at that square after a roll. For this reason it should be clear that, with the exception of G2J for which the probability + * at that square after a roll. For this reason it should be clear that, with the exception of G2J for which the probability * of finishing on it is zero, the CH squares will have the lowest probabilities, as 5/8 request a movement to another square, * and it is the final square that the player finishes at on each roll that we are interested in. We shall make no distinction * between "Just Visiting" and being sent to JAIL, and we shall also ignore the rule about requiring a double to "get out of jail", @@ -66,6 +66,8 @@ * * 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 #include #include @@ -75,8 +77,9 @@ /* 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, - 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; + 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; 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; @@ -86,261 +89,261 @@ void play(long int *count_squares); int main(int argc, char **argv) { - int i, j, max, max_i; - long int count_squares[40] = {0}; - char sq[3], *res; - double elapsed; - struct timespec start, end; + int i, j, max, max_i; + long int count_squares[40] = {0}; + char sq[3], *res; + double elapsed; + struct timespec start, end; - clock_gettime(CLOCK_MONOTONIC, &start); + clock_gettime(CLOCK_MONOTONIC, &start); - srand(time(NULL)); + srand(time(NULL)); - /* Play Monopoly.*/ - play(count_squares); + /* Play Monopoly.*/ + play(count_squares); - if((res = (char *)malloc(7*sizeof(char))) == NULL) - { - fprintf(stderr, "Error while allocating memory\n"); - return 1; - } + if((res = (char *)malloc(7*sizeof(char))) == NULL) + { + fprintf(stderr, "Error while allocating memory\n"); + return 1; + } - /* Find the three squares with maximum count.*/ - for(i = 0; i < 3; i++) - { - max = -1; + /* Find the three squares with maximum count.*/ + for(i = 0; i < 3; i++) + { + max = -1; - for(j = 0; j < 40; j++) - { - if(count_squares[j] > max) - { - max = count_squares[j]; - max_i = j; - } - } + for(j = 0; j < 40; j++) + { + if(count_squares[j] > max) + { + max = count_squares[j]; + max_i = j; + } + } - if(max_i < 10) - { - sprintf(sq, "0%d", max_i); - } - else - { - sprintf(sq, "%d", max_i); - } + if(max_i < 10) + { + sprintf(sq, "0%d", max_i); + } + else + { + 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("Answer: %s\n", res); + printf("Project Euler, Problem 84\n"); + 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.*/ void shuffle_cc(cc_card cc[]) { - int i; - cc_card c; + int i; + cc_card c; - for(i = 0; i < 16; i++) - { - cc[i] = NOP_cc; - } + for(i = 0; i < 16; i++) + { + cc[i] = NOP_cc; + } - c = GO_cc; + c = GO_cc; - do - { - do - { - i = rand() % 16; - }while(cc[i] != NOP_cc); + do + { + do + { + i = rand() % 16; + } while(cc[i] != NOP_cc); - cc[i] = c; - c++; - }while(c < NOP_cc); + cc[i] = c; + c++; + } while(c < NOP_cc); } /* Shuffle the Chance cards.*/ void shuffle_ch(ch_card ch[]) { - int i; - ch_card h; + int i; + ch_card h; - for(i = 0; i < 16; i++) - { - ch[i] = NOP_ch; - } + for(i = 0; i < 16; i++) + { + ch[i] = NOP_ch; + } - h = GO_ch; + h = GO_ch; - do - { - do - { - i = rand() % 16; - }while(ch[i] != NOP_ch); + do + { + do + { + i = rand() % 16; + } while(ch[i] != NOP_ch); - ch[i] = h; - h++; - }while(h < NOP_ch); + ch[i] = h; + h++; + } while(h < NOP_ch); } /* Function to play Monopoly, rolling the dice N times.*/ void play(long int *count_squares) { - int i, d1, d2, cc_i, ch_i, count_doubles; - squares current; - cc_card cc[16]; - ch_card ch[16]; - - /* Start from GO.*/ - current = GO; - count_squares[GO]++; - cc_i = 0; - ch_i = 0; - count_doubles = 0; + int i, d1, d2, cc_i, ch_i, count_doubles; + squares current; + cc_card cc[16]; + ch_card ch[16]; - shuffle_cc(cc); - shuffle_ch(ch); + /* Start from GO.*/ + current = GO; + count_squares[GO]++; + cc_i = 0; + ch_i = 0; + count_doubles = 0; - for(i = 0; i < N; i++) - { - /* Roll the dice.*/ - d1 = 1 + rand() % 4; - d2 = 1 + rand() % 4; + shuffle_cc(cc); + shuffle_ch(ch); - /* Check if it's a double. Increment the doubles counter if yes, - * reset it if no.*/ - if(d1 == d2) - { - count_doubles++; - } - else - { - count_doubles=0; - } + for(i = 0; i < N; i++) + { + /* Roll the dice.*/ + d1 = 1 + rand() % 4; + d2 = 1 + rand() % 4; - /* If this is the third double in a row, go to JAIL and reset - * the doubles counter.*/ - if(count_doubles == 3) - { - current = JAIL; - count_doubles = 0; - } - else - { - /* Move based on the dice roll.*/ - current = (current + d1 + d2) % 40; + /* Check if it's a double. Increment the doubles counter if yes, + * reset it if no.*/ + if(d1 == d2) + { + count_doubles++; + } + else + { + count_doubles=0; + } - /* If you get to the Go to JAIL square, go to JAIL.*/ - if(current == G2J) - { + /* If this is the third double in a row, go to JAIL and reset + * the doubles counter.*/ + if(count_doubles == 3) + { current = JAIL; - } - /* If you get to one of the Community Chest squares, get a CC card.*/ - else if(current == CC1 || current == CC2 || current == CC3) - { - /* Go to GO.*/ - if(cc[cc_i] == GO_cc) - { - current = GO; - } - /* Go to JAIL.*/ - else if(cc[cc_i] == JAIL_cc) - { - current = JAIL; - } - /* Otherwise do nothing.*/ + count_doubles = 0; + } + else + { + /* Move based on the dice roll.*/ + current = (current + d1 + d2) % 40; - 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) + /* If you get to the Go to JAIL square, go to JAIL.*/ + if(current == G2J) { - current = GO; + current = JAIL; } - /* Go to JAIL.*/ - else if(ch[ch_i] == JAIL_ch) + /* If you get to one of the Community Chest squares, get a CC card.*/ + else if(current == CC1 || current == CC2 || current == CC3) { - 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; + /* Go to GO.*/ + if(cc[cc_i] == GO_cc) + { + current = GO; + } + /* Go to JAIL.*/ + else if(cc[cc_i] == JAIL_cc) + { + current = JAIL; + } + /* Otherwise do nothing.*/ - /* 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; - } - - cc_i = (cc_i + 1) % 16; - } + 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.*/ - count_squares[current]++; - } + cc_i = (cc_i + 1) % 16; + } + } + + ch_i = (ch_i + 1) % 16; + } + } + + /* Increase the counter for the current square.*/ + count_squares[current]++; + } } diff --git a/C/p085.c b/C/p085.c index 0bfd024..7f6bc1d 100644 --- a/C/p085.c +++ b/C/p085.c @@ -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.*/ +#define _POSIX_C_SOURCE 199309L + #include #include #include @@ -10,41 +12,41 @@ int main(int argc, char **argv) { - int i, j, n, diff, min_diff = INT_MAX, area; - double elapsed; - struct timespec start, end; + int i, j, n, diff, min_diff = INT_MAX, area; + double elapsed; + struct timespec start, end; - clock_gettime(CLOCK_MONOTONIC, &start); + clock_gettime(CLOCK_MONOTONIC, &start); - for(i = 1; i < 100; i++) - { - for(j = 1; j <= i; j++) - { - /* 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 - * width, can take 6 rectangles (3 of width 1, 2 of width 2 and - * 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)= - * m(m+1)/2*n(n+1)/2=m(m+1)*n(n+1)/4 rectangles.*/ - n = ( i * (i + 1) * j * (j + 1)) / 4; - diff = abs(2000000 - n); + for(i = 1; i < 100; i++) + { + for(j = 1; j <= i; j++) + { + /* 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 + * width, can take 6 rectangles (3 of width 1, 2 of width 2 and + * 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)= + * m(m+1)/2*n(n+1)/2=m(m+1)*n(n+1)/4 rectangles.*/ + n = ( i * (i + 1) * j * (j + 1)) / 4; + diff = abs(2000000 - n); - if(diff < min_diff) - { - min_diff = diff; - area = i * j; - } - } - } - - clock_gettime(CLOCK_MONOTONIC, &end); + if(diff < min_diff) + { + min_diff = diff; + area = i * j; + } + } + } - elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; + clock_gettime(CLOCK_MONOTONIC, &end); - printf("Project Euler, Problem 85\n"); - printf("Answer: %d\n", area); + elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; - printf("Elapsed time: %.9lf seconds\n", elapsed); + printf("Project Euler, Problem 85\n"); + printf("Answer: %d\n", area); - return 0; + printf("Elapsed time: %.9lf seconds\n", elapsed); + + return 0; } diff --git a/C/p086.c b/C/p086.c index 6c80022..3be0618 100644 --- a/C/p086.c +++ b/C/p086.c @@ -9,6 +9,8 @@ * * Find the least value of M such that the number of solutions first exceeds one million.*/ +#define _POSIX_C_SOURCE 199309L + #include #include #include @@ -16,41 +18,41 @@ int main(int argc, char **argv) { - int a, b, c, count = 0; - double d, elapsed; - struct timespec start, end; + int a, b, c, count = 0; + double d, elapsed; + struct timespec start, end; - clock_gettime(CLOCK_MONOTONIC, &start); + clock_gettime(CLOCK_MONOTONIC, &start); - a = 0; + a = 0; - while(count <= 1000000) - { - a++; + while(count <= 1000000) + { + a++; - for(b = 1; b <= a; b++) - { - for(c = 1; c <= b; c++) - { - /* Unfolding the cuboid, it's obvious that the shortest path - * is the hypotenuse of a triangle, and the catheti are the - * longest side of the cubois and the sum of the other two sides.*/ - d = sqrt(a*a+(b+c)*(b+c)); + for(b = 1; b <= a; b++) + { + for(c = 1; c <= b; c++) + { + /* Unfolding the cuboid, it's obvious that the shortest path + * is the hypotenuse of a triangle, and the catheti are the + * longest side of the cubois and the sum of the other two sides.*/ + d = sqrt(a*a+(b+c)*(b+c)); - if(d == (int)d) - count++; - } - } - } + if(d == (int)d) + 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("Answer: %d\n", a); + printf("Project Euler, Problem 86\n"); + printf("Answer: %d\n", a); - printf("Elapsed time: %.9lf seconds\n", elapsed); + printf("Elapsed time: %.9lf seconds\n", elapsed); - return 0; + return 0; } diff --git a/C/p087.c b/C/p087.c index 36a1fea..8c324af 100644 --- a/C/p087.c +++ b/C/p087.c @@ -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?*/ +#define _POSIX_C_SOURCE 199309L + #include #include #include @@ -23,71 +25,71 @@ int *primes; int main(int argc, char **argv) { - int count = 0; - int *numbers; - long int i, j, k, n; - double elapsed; - struct timespec start, end; + int count = 0; + int *numbers; + long int i, j, k, n; + double elapsed; + struct timespec start, end; - clock_gettime(CLOCK_MONOTONIC, &start); + clock_gettime(CLOCK_MONOTONIC, &start); - /* Generate primes up to the square root of the limit.*/ - if((primes = sieve(SQRT_N)) == NULL) - { - fprintf(stderr, "Error! Sieve function returned NULL\n"); - return 1; - } + /* Generate primes up to the square root of the limit.*/ + if((primes = sieve(SQRT_N)) == NULL) + { + fprintf(stderr, "Error! Sieve function returned NULL\n"); + return 1; + } - if((numbers = (int *)calloc(N, sizeof(int))) == NULL) - { - fprintf(stderr, "Error while allocating memory\n"); - return 1; - } + if((numbers = (int *)calloc(N, sizeof(int))) == NULL) + { + fprintf(stderr, "Error while allocating memory\n"); + return 1; + } - /* If i>sqrt(n), i*i will be >n, so n won't be a sum of - * a square, cube and fourth power.*/ - for(i = 2; i <= SQRT_N; i++) - { - /* If i is not prime, try next number.*/ - if(primes[i]) - { - /* If j>cubic_root(n), j*j*j will be >n.*/ - for(j = 2; j <= RAD3_N; j++) - { - if(primes[j]) + /* If i>sqrt(n), i*i will be >n, so n won't be a sum of + * a square, cube and fourth power.*/ + for(i = 2; i <= SQRT_N; i++) + { + /* If i is not prime, try next number.*/ + if(primes[i]) + { + /* If j>cubic_root(n), j*j*j will be >n.*/ + for(j = 2; j <= RAD3_N; j++) { - /* If k>fourth_root(n), k*k*k*k will be >n.*/ - for(k = 2; k <= RAD4_N; k++) - { - if(primes[k]) - { - n = i * i + j * j * j + k * k * k * k; + if(primes[j]) + { + /* If k>fourth_root(n), k*k*k*k will be >n.*/ + for(k = 2; k <= RAD4_N; k++) + { + if(primes[k]) + { + n = i * i + j * j * j + k * k * k * k; - /* Check if the number found is lower than the limit, - * and make sure it hasn't been found before.*/ - if(n < N && numbers[n] == 0) - { - count++; - numbers[n] = 1; - } - } - } + /* Check if the number found is lower than the limit, + * and make sure it hasn't been found before.*/ + if(n < N && numbers[n] == 0) + { + count++; + numbers[n] = 1; + } + } + } + } } - } - } - } + } + } - free(primes); - free(numbers); - - clock_gettime(CLOCK_MONOTONIC, &end); - - elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; - - printf("Project Euler, Problem 87\n"); - printf("Answer: %d\n", count); + free(primes); + free(numbers); - printf("Elapsed time: %.9lf seconds\n", elapsed); - - return 0; + clock_gettime(CLOCK_MONOTONIC, &end); + + elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; + + printf("Project Euler, Problem 87\n"); + printf("Answer: %d\n", count); + + printf("Elapsed time: %.9lf seconds\n", elapsed); + + return 0; } diff --git a/C/p089.c b/C/p089.c index 684212c..9bc399d 100644 --- a/C/p089.c +++ b/C/p089.c @@ -19,6 +19,8 @@ * * 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 #include #include @@ -28,81 +30,81 @@ int reduce(char *numeral, int l); int main(int argc, char **argv) { - int i, l, count = 0, count_reduced = 0; - char *numerals[1000]; - double elapsed; - struct timespec start, end; - FILE *fp; + int i, l, count = 0, count_reduced = 0; + char *numerals[1000]; + double elapsed; + struct timespec start, end; + FILE *fp; - clock_gettime(CLOCK_MONOTONIC, &start); + clock_gettime(CLOCK_MONOTONIC, &start); - if((fp = fopen("roman.txt", "r")) == NULL) - { - fprintf(stderr, "Error while opening file %s\n", "roman.txt"); - return 1; - } + if((fp = fopen("roman.txt", "r")) == NULL) + { + fprintf(stderr, "Error while opening file %s\n", "roman.txt"); + return 1; + } - /* 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 - * of the two lengths.*/ - for(i = 0; i < 1000; i++) - { - fscanf(fp, "%ms", &numerals[i]); - l = strlen(numerals[i]); - count += l; - l = reduce(numerals[i], l); - count_reduced += l; - free(numerals[i]); - } + /* 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 + * of the two lengths.*/ + for(i = 0; i < 1000; i++) + { + fscanf(fp, "%ms", &numerals[i]); + l = strlen(numerals[i]); + count += l; + l = reduce(numerals[i], l); + count_reduced += l; + 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("Answer: %d\n", count-count_reduced); + printf("Project Euler, Problem 89\n"); + 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) { - /* DCCCC = CM.*/ - if(strstr(numeral, "DCCCC") != NULL) - { - l -= 3; - } - /* CCCC = CD.*/ - else if(strstr(numeral, "CCCC") != NULL) - { - l -= 2; - } + /* DCCCC = CM.*/ + if(strstr(numeral, "DCCCC") != NULL) + { + l -= 3; + } + /* CCCC = CD.*/ + else if(strstr(numeral, "CCCC") != NULL) + { + l -= 2; + } - /* LXXXX = XC.*/ - if(strstr(numeral, "LXXXX") != NULL) - { - l -= 3; - } - /* XXXX = XL.*/ - else if(strstr(numeral, "XXXX") != NULL) - { - l -= 2; - } + /* LXXXX = XC.*/ + if(strstr(numeral, "LXXXX") != NULL) + { + l -= 3; + } + /* XXXX = XL.*/ + else if(strstr(numeral, "XXXX") != NULL) + { + l -= 2; + } - /* VIIII = IX.*/ - if(strstr(numeral, "VIIII") != NULL) - { - l -= 3; - } - /* IIII = IV.*/ - else if(strstr(numeral, "IIII") != NULL) - { - l -= 2; - } + /* VIIII = IX.*/ + if(strstr(numeral, "VIIII") != NULL) + { + l -= 3; + } + /* IIII = IV.*/ + else if(strstr(numeral, "IIII") != NULL) + { + l -= 2; + } - return l; + return l; } diff --git a/C/p092.c b/C/p092.c index 9082409..bb7d59d 100644 --- a/C/p092.c +++ b/C/p092.c @@ -10,6 +10,8 @@ * * How many starting numbers below ten million will arrive at 89?*/ +#define _POSIX_C_SOURCE 199309L + #include #include #include @@ -22,63 +24,63 @@ int chain(int n); int main(int argc, char **argv) { - int i, count = 0; - double elapsed; - struct timespec start, end; + int i, count = 0; + double elapsed; + struct timespec start, end; - clock_gettime(CLOCK_MONOTONIC, &start); + clock_gettime(CLOCK_MONOTONIC, &start); - for(i = 1; i < N; i++) - { - /* Simply create a chain for each number and check if it ends at 89, saving - * the result so it can be reused.*/ - if((chains[i] = chain(i)) == 89) - { - count++; - } - } + for(i = 1; i < N; i++) + { + /* Simply create a chain for each number and check if it ends at 89, saving + * the result so it can be reused.*/ + if((chains[i] = chain(i)) == 89) + { + 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("Answer: %d\n", count); + printf("Project Euler, Problem 92\n"); + 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.*/ 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) - { - return 1; - } + /* If n=1 or n=89, we reached the end of the chain.*/ + if(n == 1) + { + return 1; + } - if(n == 89) - { - return 89; - } + if(n == 89) + { + return 89; + } - /* If the chain for the current n has already been found, - * return the value.*/ - if(chains[n] != 0) - { - return chains[n]; - } + /* If the chain for the current n has already been found, + * return the value.*/ + if(chains[n] != 0) + { + return chains[n]; + } - while(n > 0) - { - digit = n % 10; - tmp += digit * digit; - n /= 10; - } + while(n > 0) + { + digit = n % 10; + tmp += digit * digit; + n /= 10; + } - return chain(tmp); + return chain(tmp); } diff --git a/C/p095.c b/C/p095.c index b581ec2..d2575ef 100644 --- a/C/p095.c +++ b/C/p095.c @@ -12,6 +12,8 @@ * * Find the smallest member of the longest amicable chain with no element exceeding one million.*/ +#define _POSIX_C_SOURCE 199309L + #include #include #include @@ -26,99 +28,99 @@ int divisors[N] = {0}; int main(int argc, char **argv) { - int i, min = 0, min_tmp, length, l_max = 0; - int chain[100]; - double elapsed; - struct timespec start, end; + int i, min = 0, min_tmp, length, l_max = 0; + int chain[100]; + double elapsed; + struct timespec start, end; - clock_gettime(CLOCK_MONOTONIC, &start); + clock_gettime(CLOCK_MONOTONIC, &start); - for(i = 4; i <= N; i++) - { - /* 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.*/ - if((divisors[i] = sum_of_divisors(i, 1)) == i) - { - continue; - } - else - { - min_tmp = i; - length = sociable_chain(i, chain, 0, &min_tmp); - } - - if(length > l_max) - { - l_max = length; - min = min_tmp; - } - } + for(i = 4; i <= N; i++) + { + /* 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.*/ + if((divisors[i] = sum_of_divisors(i, 1)) == i) + { + continue; + } + else + { + min_tmp = i; + length = sociable_chain(i, chain, 0, &min_tmp); + } - clock_gettime(CLOCK_MONOTONIC, &end); + if(length > l_max) + { + l_max = length; + min = min_tmp; + } + } - elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; + clock_gettime(CLOCK_MONOTONIC, &end); - printf("Project Euler, Problem 95\n"); - printf("Answer: %d\n", min); + elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; - printf("Elapsed time: %.9lf seconds\n", elapsed); + printf("Project Euler, Problem 95\n"); + printf("Answer: %d\n", min); - return 0; + printf("Elapsed time: %.9lf seconds\n", elapsed); + + return 0; } /* Function to recursively find the length of the chain.*/ int sociable_chain(int i, int *chain, int l, int *min) { - int n; + int n; - /* Save current number in the chain.*/ - chain[l] = i; + /* Save current number in the chain.*/ + chain[l] = i; - /* If we reached 1, the chain will never go anywhere.*/ - if(i == 1) - { - return -1; - } + /* If we reached 1, the chain will never go anywhere.*/ + if(i == 1) + { + return -1; + } - /* Calculate the divisors of i, or retrieve the value if previously calculated.*/ - if(divisors[i] != 0) - { - n = divisors[i]; - } - else - { - n = sum_of_divisors(i, 1); - divisors[i] = n; - } - - /* We are looking for chain where no value is greater than 1000000.*/ - if(n > N) - { - return -1; - } + /* Calculate the divisors of i, or retrieve the value if previously calculated.*/ + if(divisors[i] != 0) + { + n = divisors[i]; + } + else + { + n = sum_of_divisors(i, 1); + divisors[i] = n; + } - /* If the next number in the chain is equal to the starting one, the chain is finished.*/ - if(n == chain[0]) - { - return l + 1; - } + /* We are looking for chain where no value is greater than 1000000.*/ + if(n > N) + { + return -1; + } - /* 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.*/ - for(i = l; i > 0; i--) - { - if(n == chain[i]) - { - return -1; - } - } + /* If the next number in the chain is equal to the starting one, the chain is finished.*/ + if(n == chain[0]) + { + return l + 1; + } - /* If the next value is smaller than the minimum value of the chain, - * update the minimum.*/ - if(n < *min) - { - *min = n; - } + /* 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.*/ + for(i = l; i > 0; i--) + { + if(n == chain[i]) + { + return -1; + } + } - return sociable_chain(n, chain, l+1, min); + /* If the next value is smaller than the minimum value of the chain, + * update the minimum.*/ + if(n < *min) + { + *min = n; + } + + return sociable_chain(n, chain, l+1, min); } diff --git a/C/p096.c b/C/p096.c index 0bba9b3..d6bc200 100644 --- a/C/p096.c +++ b/C/p096.c @@ -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; * 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 #include #include @@ -35,266 +37,266 @@ int check(int grid[][9], int i, int j, int n); int main(int argc, char **argv) { - char dummy[10], dummy_c; - int i, j, sum = 0, partial; - int grid[9][9]; - double elapsed; - struct timespec start, end; - FILE *fp; + char dummy[10], dummy_c; + int i, j, sum = 0, partial; + int grid[9][9]; + double elapsed; + struct timespec start, end; + FILE *fp; - clock_gettime(CLOCK_MONOTONIC, &start); + clock_gettime(CLOCK_MONOTONIC, &start); - if((fp = fopen("sudoku.txt", "r")) == NULL) - { - fprintf(stderr, "Error while opening file %s\n", "sudoku.txt"); - return 1; - } + if((fp = fopen("sudoku.txt", "r")) == NULL) + { + fprintf(stderr, "Error while opening file %s\n", "sudoku.txt"); + return 1; + } - while(!feof(fp)) - { - fgets(dummy, sizeof(dummy), fp); + while(!feof(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'; - } - - fscanf(fp, "%c", &dummy_c); - } + 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 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; - } + fscanf(fp, "%c", &dummy_c); + } - partial = grid[0][0] * 100 + grid[0][1] * 10 + grid[0][2]; - sum += partial; - } + /* 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; + } - fclose(fp); + partial = grid[0][0] * 100 + grid[0][1] * 10 + grid[0][2]; + sum += partial; + } - clock_gettime(CLOCK_MONOTONIC, &end); + fclose(fp); - 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); + 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 96\n"); + printf("Answer: %d\n", sum); + + printf("Elapsed time: %.9lf seconds\n", elapsed); + + return 0; } 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++) - { - 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) - { + for(k = 0; k < 9; k++) + { + if(k != j && grid[i][k] == n) + { 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 i, j, k; + int i, j, k; - if(step == 81) - { - return 1; - } + if(step == 81) + { + return 1; + } - i = step / 9; - j = step % 9; + i = step / 9; + j = step % 9; - if(grid[i][j] != 0) - { - if(solve_recursive(grid, step+1)) - { - return 1; - } - } - else - { - for(k = 1; k <= 9; k++) - { - grid[i][j] = k; + if(grid[i][j] != 0) + { + if(solve_recursive(grid, step+1)) + { + return 1; + } + } + else + { + for(k = 1; k <= 9; k++) + { + grid[i][j] = k; - if(check(grid, i, j, k)) - { - if(solve_recursive(grid, step+1)) + if(check(grid, i, j, k)) { - 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 n; + int n; - for(n = 0; n < 9; n++) - { - if(grid[i][n] == 0) - { - return 0; - } - } + for(n = 0; n < 9; n++) + { + if(grid[i][n] == 0) + { + return 0; + } + } - return 1; + return 1; } int column_complete(int grid[][9], int j) { - int n; + int n; - for(n = 0; n < 9; n++) - { - if(grid[n][j] == 0) - { - return 0; - } - } + for(n = 0; n < 9; n++) + { + if(grid[n][j] == 0) + { + return 0; + } + } - return 1; + return 1; } 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(i = 0; i < 9; i++) - { - for(j = 0; j < 9; j++) - { - if(grid[i][j] == 0) + for(w = 0; w < 4; w++) + { + for(i = 0; i < 9; i++) + { + for(j = 0; j < 9; j++) { - count = 0; - - for(k = 1; k <= 9 && count < 2; k++) - { - grid[i][j] = k; + if(grid[i][j] == 0) + { + count = 0; - if(check(grid, i, j, k) == 1) - { - count++; - val = k; - } - } + for(k = 1; k <= 9 && count < 2; k++) + { + grid[i][j] = k; - if(count == 1) - { - grid[i][j] = val; - } - else - { - grid[i][j] = 0; - } + if(check(grid, i, j, k) == 1) + { + count++; + val = k; + } + } + + if(count == 1) + { + grid[i][j] = val; + } + else + { + grid[i][j] = 0; + } + } } - } - } + } - for(i = 0; i < 9; i++) - { - for(k = 1; k <= 9 && !line_complete(grid, i); k++) - { - count = 0; - - for(j = 0; j < 9 && count < 2; j++) + for(i = 0; i < 9; i++) + { + for(k = 1; k <= 9 && !line_complete(grid, i); k++) { - if(grid[i][j] == 0) - { - grid[i][j] = k; + count = 0; - if(check(grid, i, j, k)) - { - count++; - val = j; - } + for(j = 0; j < 9 && count < 2; j++) + { + if(grid[i][j] == 0) + { + 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++) - { - 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); + return solve_recursive(grid, 0); } diff --git a/C/p097.c b/C/p097.c index 500a260..2f5a274 100644 --- a/C/p097.c +++ b/C/p097.c @@ -5,44 +5,46 @@ * * Find the last ten digits of this prime number.*/ +#define _POSIX_C_SOURCE 199309L + #include #include #include int main(int argc, char **argv) { - int b = 2, e = 7830457, e_first; - long int m = 10000000000, c, result; - double elapsed; - struct timespec start, end; + int b = 2, e = 7830457, e_first; + long int m = 10000000000, c, result; + double elapsed; + 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: - * Set c=1, e'=0 - * Increment e' by 1 - * Set c=b*c%m, where b is the base (2) and m is the modulo (10000000000 since - * we want the last 10 digits. - * If e' 519432^525806 would be much more difficult, as both numbers contain over three million digits. * - * Using base_exp.txt, a 22K text file containing one thousand lines with a base/exponent pair on each line, + * Using base_exp.txt, a 22K text file containing one thousand lines with a base/exponent pair on each line, * determine which line number has the greatest numerical value. * * NOTE: The first two lines in the file represent the numbers in the example given above.*/ +#define _POSIX_C_SOURCE 199309L + #include #include #include @@ -15,46 +17,46 @@ int main(int argc, char **argv) { - int i, max_i = -1, base, exp; - double curr, max = 0, elapsed; - struct timespec start, end; - FILE *fp; + int i, max_i = -1, base, exp; + double curr, max = 0, elapsed; + struct timespec start, end; + FILE *fp; - clock_gettime(CLOCK_MONOTONIC, &start); + clock_gettime(CLOCK_MONOTONIC, &start); - if((fp = fopen("base_exp.txt", "r")) == NULL) - { - fprintf(stderr, "Error while opening file %s\n", "base_exp.txt"); - return 1; - } + if((fp = fopen("base_exp.txt", "r")) == NULL) + { + fprintf(stderr, "Error while opening file %s\n", "base_exp.txt"); + return 1; + } - for(i = 1; i <= 1000; i++) - { - fscanf(fp, "%d,%d", &base, &exp); - /* If - * a^x > b^y - * log(a^x) > log(b^y) - * x*log(a) > y*log(b). - * So for each b^e, calculate e*log(b) and compare these numbers instead.*/ - curr = exp * log(base); + for(i = 1; i <= 1000; i++) + { + fscanf(fp, "%d,%d", &base, &exp); + /* If + * a^x > b^y + * log(a^x) > log(b^y) + * x*log(a) > y*log(b). + * So for each b^e, calculate e*log(b) and compare these numbers instead.*/ + curr = exp * log(base); - if(curr > max) - { - max = curr; - max_i = i; - } - } + if(curr > max) + { + max = curr; + max_i = i; + } + } - fclose(fp); - - clock_gettime(CLOCK_MONOTONIC, &end); + fclose(fp); - elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; + clock_gettime(CLOCK_MONOTONIC, &end); - printf("Project Euler, Problem 99\n"); - printf("Answer: %d\n", max_i); + elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; - printf("Elapsed time: %.9lf seconds\n", elapsed); + printf("Project Euler, Problem 99\n"); + printf("Answer: %d\n", max_i); - return 0; + printf("Elapsed time: %.9lf seconds\n", elapsed); + + return 0; } diff --git a/C/p102.c b/C/p102.c index 80433f7..04bb3b5 100644 --- a/C/p102.c +++ b/C/p102.c @@ -12,6 +12,8 @@ * * NOTE: The first two examples in the file represent the triangles in the example given above.*/ +#define _POSIX_C_SOURCE 199309L + #include #include #include @@ -19,51 +21,51 @@ typedef struct point { - int x; - int y; -}point; + int x; + int y; +} point; int main(int argc, char **argv) { - int count = 0; - FILE *fp; - point p1, p2, p3; - double a, b, c, elapsed; - struct timespec start, end; + int count = 0; + FILE *fp; + point p1, p2, p3; + double a, b, c, elapsed; + struct timespec start, end; - clock_gettime(CLOCK_MONOTONIC, &start); + clock_gettime(CLOCK_MONOTONIC, &start); - if((fp = fopen("triangles.txt", "r")) == NULL) - { - fprintf(stderr, "Error while opening file %s\n", "triangles.txt"); - return 1; - } + if((fp = fopen("triangles.txt", "r")) == NULL) + { + fprintf(stderr, "Error while opening file %s\n", "triangles.txt"); + return 1; + } - /* 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) - { - 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)); - 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)); - c = 1 - a - b; + /* 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) + { + 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)); + 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)); + c = 1 - a - b; - if(a >= 0 && a <= 1 && b >= 0 && b <= 1 && c >= 0 && c <= 1) - { - count++; - } - } + if(a >= 0 && a <= 1 && b >= 0 && b <= 1 && c >= 0 && c <= 1) + { + 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("Answer: %d\n", count); + printf("Project Euler, Problem 102\n"); + printf("Answer: %d\n", count); - printf("Elapsed time: %.9lf seconds\n", elapsed); + printf("Elapsed time: %.9lf seconds\n", elapsed); - return 0; + return 0; } diff --git a/C/p104.c b/C/p104.c index 20f3fe6..3ca0605 100644 --- a/C/p104.c +++ b/C/p104.c @@ -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.*/ +#define _POSIX_C_SOURCE 199309L + #include #include #include @@ -17,101 +19,101 @@ void fib_calc(mpz_t fib, int n); int main(int argc, char **argv) { - unsigned int i = 2, j, fib1 = 1, fib2 = 1, fibn, fib_int, found = 0; - char *fib_str; - double elapsed; - struct timespec start, end; - mpz_t fib; + unsigned int i = 2, j, fib1 = 1, fib2 = 1, fibn, fib_int, found = 0; + char *fib_str; + double elapsed; + struct timespec start, end; + mpz_t fib; - clock_gettime(CLOCK_MONOTONIC, &start); + clock_gettime(CLOCK_MONOTONIC, &start); - mpz_init(fib); + mpz_init(fib); - while(!found) - { - /* Calculate the next Fibonacci number modulo 10^9 and check if the result is 1-9 pandigital.*/ - fibn = (fib1 + fib2) % 1000000000; - fib1 = fib2; - fib2 = fibn; - i++; - - /* If the last 9 digits of fib_n are pandigital, calculate the ith Fibonacci number using - * the matrix representation.*/ - if(is_pandigital(fibn, 9)) - { - fib_calc(fib, i); - fib_str = mpz_get_str(NULL, 10, fib); + while(!found) + { + /* Calculate the next Fibonacci number modulo 10^9 and check if the result is 1-9 pandigital.*/ + fibn = (fib1 + fib2) % 1000000000; + fib1 = fib2; + fib2 = fibn; + i++; - fib_int = 0; + /* If the last 9 digits of fib_n are pandigital, calculate the ith Fibonacci number using + * the matrix representation.*/ + if(is_pandigital(fibn, 9)) + { + fib_calc(fib, i); + fib_str = mpz_get_str(NULL, 10, fib); - for(j = 0; j < 9; j++) - { - fib_int *= 10; - fib_int += fib_str[j] - '0'; - } + fib_int = 0; - if(is_pandigital(fib_int, 9)) - { - found = 1; - } + for(j = 0; j < 9; j++) + { + fib_int *= 10; + fib_int += fib_str[j] - '0'; + } - free(fib_str); - } - } + if(is_pandigital(fib_int, 9)) + { + found = 1; + } - mpz_clear(fib); + free(fib_str); + } + } - clock_gettime(CLOCK_MONOTONIC, &end); + mpz_clear(fib); - elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; + clock_gettime(CLOCK_MONOTONIC, &end); - printf("Project Euler, Problem 104\n"); - printf("Answer: %d\n", i); + elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; - printf("Elapsed time: %.9lf seconds\n", elapsed); + printf("Project Euler, Problem 104\n"); + printf("Answer: %d\n", i); - return 0; + printf("Elapsed time: %.9lf seconds\n", elapsed); + + return 0; } void fib_calc(mpz_t fib, int n) { - int i; - mpz_t tmp, tmp00, tmp01, tmp10, tmp11; - mpz_t fib_matrix_base[2][2], fib_matrix[2][2]; + int i; + mpz_t tmp, tmp00, tmp01, tmp10, tmp11; + 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][1], 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[0][0], 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][1], 0); - mpz_inits(tmp, tmp00, tmp01, tmp10, tmp11, NULL); + 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[1][0], 1); + 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][1], 1); + mpz_init_set_ui(fib_matrix[1][0], 1); + mpz_init_set_ui(fib_matrix[1][1], 0); + mpz_inits(tmp, tmp00, tmp01, tmp10, tmp11, NULL); - for(i = 0; i < n - 1; i++) - { - 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_add(tmp00, tmp00, tmp); - 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_add(tmp01, tmp01, tmp); - 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_add(tmp10, tmp10, tmp); - 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_add(tmp11, tmp11, tmp); - mpz_set(fib_matrix[0][0], tmp00); - mpz_set(fib_matrix[0][1], tmp01); - mpz_set(fib_matrix[1][0], tmp10); - mpz_set(fib_matrix[1][1], tmp11); - } + for(i = 0; i < n - 1; i++) + { + 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_add(tmp00, tmp00, tmp); + 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_add(tmp01, tmp01, tmp); + 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_add(tmp10, tmp10, tmp); + 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_add(tmp11, tmp11, tmp); + mpz_set(fib_matrix[0][0], tmp00); + mpz_set(fib_matrix[0][1], tmp01); + mpz_set(fib_matrix[1][0], tmp10); + 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], - 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); + 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[0][0], fib_matrix[1][0], fib_matrix[1][1], NULL); } diff --git a/C/p112.c b/C/p112.c index 1d2c344..3b7405a 100644 --- a/C/p112.c +++ b/C/p112.c @@ -11,6 +11,8 @@ * * Find the least number for which the proportion of bouncy numbers is exactly 99%.*/ +#define _POSIX_C_SOURCE 199309L + #include #include #include @@ -20,88 +22,88 @@ int is_bouncy(int n); int main(int argc, char **argv) { - int i = 100, n_bouncy = 0; - double ratio = 0.0, elapsed; - struct timespec start, end; + int i = 100, n_bouncy = 0; + double ratio = 0.0, elapsed; + struct timespec start, end; - clock_gettime(CLOCK_MONOTONIC, &start); + clock_gettime(CLOCK_MONOTONIC, &start); - while(1) - { - if(is_bouncy(i)) - { - n_bouncy++; - } + while(1) + { + if(is_bouncy(i)) + { + n_bouncy++; + } - ratio = (double)n_bouncy / i; - - if(ratio == 0.99) - { - break; - } - - i++; - } + ratio = (double)n_bouncy / i; - clock_gettime(CLOCK_MONOTONIC, &end); + if(ratio == 0.99) + { + break; + } - elapsed = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1000000000; + i++; + } - printf("Project Euler, Problem 112\n"); - printf("Answer: %d\n", i); + 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 112\n"); + printf("Answer: %d\n", i); + + printf("Elapsed time: %.9lf seconds\n", elapsed); + + return 0; } /* Check if the number is bouncy.*/ int is_bouncy(int n) { - int i = 0, l; - char n_string[100]; + int i = 0, l; + 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.*/ - while(i < l - 1 && n_string[i] == n_string[i+1]) - { - i++; - } + /* Ignore consecutive equal digits.*/ + while(i < l - 1 && n_string[i] == n_string[i+1]) + { + i++; + } - /* If all the digits are the same, the number is not bouncy.*/ - if(i == l - 1) - { - return 0; - } + /* If all the digits are the same, the number is not bouncy.*/ + if(i == l - 1) + { + return 0; + } - /* If the first two different digits are increasing, if a successive - * digit smaller than the previous digit is found, the number is bouncy.*/ - if(n_string[i] < n_string[i+1]) - { - for(; i < l - 1; i++) - { - if(n_string[i] > n_string[i+1]) - { - return 1; - } - } - } + /* If the first two different digits are increasing, if a successive + * digit smaller than the previous digit is found, the number is bouncy.*/ + if(n_string[i] < n_string[i+1]) + { + for(; i < l - 1; i++) + { + if(n_string[i] > n_string[i+1]) + { + return 1; + } + } + } - /* If the first two different digits are decreasing, if a successive - * digit larger than the previous digit is found, the number is bouncy.*/ - if(n_string[i] > n_string[i+1]) - { - for(; i < l - 1; i++) - { - if(n_string[i] < n_string[i+1]) - { - return 1; - } - } - } + /* If the first two different digits are decreasing, if a successive + * digit larger than the previous digit is found, the number is bouncy.*/ + if(n_string[i] > n_string[i+1]) + { + for(; i < l - 1; i++) + { + if(n_string[i] < n_string[i+1]) + { + return 1; + } + } + } - return 0; + return 0; } diff --git a/C/p124.c b/C/p124.c index a4f256d..15dfbe8 100644 --- a/C/p124.c +++ b/C/p124.c @@ -2,7 +2,7 @@ * * If we calculate rad(n) for 1 ≤ n ≤ 10, then sort them on rad(n), and sorting on n if the radical values are equal, we get: * - * Unsorted Sorted + * Unsorted Sorted * n rad(n) n rad(n) k * 1 1 1 1 1 * 2 2 2 2 2 @@ -19,6 +19,8 @@ * * If rad(n) is sorted for 1 ≤ n ≤ 100000, find E(10000).*/ +#define _POSIX_C_SOURCE 199309L + #include #include #include @@ -29,77 +31,77 @@ typedef struct n_rad { - int n; - int radn; -}n_radn; + int n; + int radn; +} n_radn; int compare(void *a, void *b); int main(int argc, char **argv) { - int i, *primes; - n_radn **rads; - double elapsed; - struct timespec start, end; + int i, *primes; + n_radn **rads; + double elapsed; + struct timespec start, end; - clock_gettime(CLOCK_MONOTONIC, &start); + clock_gettime(CLOCK_MONOTONIC, &start); - if((primes = sieve(N)) == NULL) - { - fprintf(stderr, "Error! Sieve function returned NULL\n"); - return 1; - } + if((primes = sieve(N)) == NULL) + { + fprintf(stderr, "Error! Sieve function returned NULL\n"); + return 1; + } - if((rads = (n_radn **)malloc(N*sizeof(n_radn *))) == NULL) - { - fprintf(stderr, "Error while allocating memory\n"); - return 1; - } + if((rads = (n_radn **)malloc(N*sizeof(n_radn *))) == NULL) + { + fprintf(stderr, "Error while allocating memory\n"); + return 1; + } - for(i = 0; i < N; i++) - { - if((rads[i] = (n_radn *)malloc(sizeof(n_radn))) == NULL) - { - fprintf(stderr, "Error while allocating memory\n"); - return 1; - } - } + for(i = 0; i < N; i++) + { + if((rads[i] = (n_radn *)malloc(sizeof(n_radn))) == NULL) + { + fprintf(stderr, "Error while allocating memory\n"); + return 1; + } + } - for(i = 0; i < N; i++) - { - rads[i]->n = i + 1; - rads[i]->radn = radical(i+1, primes); - } + for(i = 0; i < N; i++) + { + rads[i]->n = i + 1; + 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("Answer: %d\n", rads[9999]->n); + printf("Project Euler, Problem 124\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) { - n_radn *rad1, *rad2; + n_radn *rad1, *rad2; - rad1 = (n_radn *)a; - rad2 = (n_radn *)b; + rad1 = (n_radn *)a; + rad2 = (n_radn *)b; - if(rad1->radn != rad2->radn) - { - return rad1->radn - rad2->radn; - } - else - { - return rad1->n - rad2->n; - } + if(rad1->radn != rad2->radn) + { + return rad1->radn - rad2->radn; + } + else + { + return rad1->n - rad2->n; + } } diff --git a/C/p145.c b/C/p145.c index 496c240..7832017 100644 --- a/C/p145.c +++ b/C/p145.c @@ -6,6 +6,8 @@ * * How many reversible numbers are there below one-billion (109)?*/ +#define _POSIX_C_SOURCE 199309L + #include #include #include @@ -16,58 +18,58 @@ int reverse(int n); int main(int argc, char **argv) { - int i, s, count = 0; - double elapsed; - struct timespec start, end; + int i, s, count = 0; + double elapsed; + struct timespec start, end; - clock_gettime(CLOCK_MONOTONIC, &start); + clock_gettime(CLOCK_MONOTONIC, &start); - /* Brute force approach, sum each number and their reverse and - * check if there are only odd digits.*/ - for(i = 11; i < N; i++) - { - if(i % 10 != 0) - { - s = i + reverse(i); + /* Brute force approach, sum each number and their reverse and + * check if there are only odd digits.*/ + for(i = 11; i < N; i++) + { + if(i % 10 != 0) + { + s = i + reverse(i); - while(s > 0) - { - if((s % 10) % 2 == 0) + while(s > 0) { - break; + if((s % 10) % 2 == 0) + { + break; + } + s /= 10; } - s /= 10; - } - if(s == 0) - { - count++; - } - } - } + if(s == 0) + { + 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("Answer: %d\n", count); + printf("Project Euler, Problem 145\n"); + 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 = 0; + int reverse = 0; - while(n > 0) - { - reverse *= 10; - reverse += n % 10; - n /= 10; - } + while(n > 0) + { + reverse *= 10; + reverse += n % 10; + n /= 10; + } - return reverse; + return reverse; } diff --git a/C/p206.c b/C/p206.c index 47e6360..5c98eae 100644 --- a/C/p206.c +++ b/C/p206.c @@ -1,60 +1,62 @@ /* 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.*/ +#define _POSIX_C_SOURCE 199309L + #include #include #include int main(int argc, char **argv) { - int i, found = 0; - /* Since the square of n has 19 digits, n must be at least 10^9.*/ - long int n = 1e9, p; - double elapsed; - struct timespec start, end; + int i, found = 0; + /* Since the square of n has 19 digits, n must be at least 10^9.*/ + long int n = 1e9, p; + double elapsed; + struct timespec start, end; - clock_gettime(CLOCK_MONOTONIC, &start); + clock_gettime(CLOCK_MONOTONIC, &start); - while(!found) - { - /* If the square on n ends with 10, n must be divisible by 10.*/ - n += 10; - p = n * n; + while(!found) + { + /* If the square on n ends with 10, n must be divisible by 10.*/ + n += 10; + p = n * n; - /* A square divisible by 10 is also divisible by 100.*/ - if(p % 100 != 0) - { - continue; - } + /* A square divisible by 10 is also divisible by 100.*/ + if(p % 100 != 0) + { + continue; + } - /* Check if the digits of the square correspond to the given pattern.*/ - i = 9; - p /= 100; + /* Check if the digits of the square correspond to the given pattern.*/ + i = 9; + p /= 100; - while(p > 0) - { - if(p % 10 != i) - { - break; - } - p /= 100; - i--; - } + while(p > 0) + { + if(p % 10 != i) + { + break; + } + p /= 100; + i--; + } - if(p == 0) - { - found = 1; - } - } + if(p == 0) + { + 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("Answer: %ld\n", n); + printf("Project Euler, Problem 206\n"); + printf("Answer: %ld\n", n); - printf("Elapsed time: %.9lf seconds\n", elapsed); + printf("Elapsed time: %.9lf seconds\n", elapsed); - return 0; + return 0; } diff --git a/C/p357.c b/C/p357.c index b815186..b29e334 100644 --- a/C/p357.c +++ b/C/p357.c @@ -4,6 +4,8 @@ * Find the sum of all positive integers n not exceeding 100 000 000 * such that for every divisor d of n, d+n/d is prime.*/ +#define _POSIX_C_SOURCE 199309L + #include #include #include @@ -18,61 +20,61 @@ int *primes; int main(int argc, char **argv) { - int i; - long int sum = 1; - double elapsed; - struct timespec start, end; + int i; + long int sum = 1; + double elapsed; + struct timespec start, end; - clock_gettime(CLOCK_MONOTONIC, &start); + clock_gettime(CLOCK_MONOTONIC, &start); - if((primes = sieve(N+2)) == NULL) - { - fprintf(stderr, "Error! Sieve function returned NULL\n"); - return 1; - } + if((primes = sieve(N+2)) == NULL) + { + fprintf(stderr, "Error! Sieve function returned NULL\n"); + return 1; + } - for(i = 2; i <= N; i += 2) - { - /* Every number is divisible by 1, so 1+n/1=n+1 must be prime.*/ - if(primes[i+1] && check_d_nd_prime(i)) - { - sum += i; - } - } + for(i = 2; i <= N; i += 2) + { + /* Every number is divisible by 1, so 1+n/1=n+1 must be prime.*/ + if(primes[i+1] && check_d_nd_prime(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 357\n"); - printf("Answer: %ld\n", sum); + printf("Project Euler, Problem 357\n"); + printf("Answer: %ld\n", sum); - printf("Elapsed time: %.9lf seconds\n", elapsed); + printf("Elapsed time: %.9lf seconds\n", elapsed); - return 0; + return 0; } int check_d_nd_prime(int n) { - int i, limit; + int i, limit; - /* To get all divisors, it's sufficient to loop up to the square root - * of the number, because for every divisor d smaller than sqrt(n) n/d - * is also a divisor larger than sqrt(n).*/ - limit = floor(sqrt(n)); + /* To get all divisors, it's sufficient to loop up to the square root + * of the number, because for every divisor d smaller than sqrt(n) n/d + * is also a divisor larger than sqrt(n).*/ + limit = floor(sqrt(n)); - for(i = 2; i <= limit; i++) - { - if(n % i == 0) - { - /* We only need to check the property for i and not n/i. - * If d=n/i, we would have to check if n/i+n/(n/i)=n/i+i is prime.*/ - if(!primes[i+n/i]) - { - return 0; - } - } - } + for(i = 2; i <= limit; i++) + { + if(n % i == 0) + { + /* We only need to check the property for i and not n/i. + * If d=n/i, we would have to check if n/i+n/(n/i)=n/i+i is prime.*/ + if(!primes[i+n/i]) + { + return 0; + } + } + } - return 1; + return 1; } diff --git a/C/projecteuler.c b/C/projecteuler.c index da72f6d..7396fc2 100644 --- a/C/projecteuler.c +++ b/C/projecteuler.c @@ -8,476 +8,476 @@ int partition(void **array, int l, int r, int (*cmp)(void *lv, void *rv)); int is_prime(long int num) { - long int i, limit; + long int i, limit; - if(num <= 3) - { - /* If num is 2 or 3 then it's prime.*/ - return num == 2 || num == 3; - } + if(num <= 3) + { + /* If num is 2 or 3 then it's prime.*/ + return num == 2 || num == 3; + } - /* If num is divisible by 2 or 3 then it's not prime.*/ - if(num % 2 == 0 || num % 3 == 0) - { - return 0; - } + /* If num is divisible by 2 or 3 then it's not prime.*/ + if(num % 2 == 0 || num % 3 == 0) + { + return 0; + } - /* Any number can have only one prime factor greater than its - * square root. If we reach the square root and we haven't found - * any smaller prime factors, then the number is prime.*/ - limit = floor(sqrt(num)); + /* Any number can have only one prime factor greater than its + * square root. If we reach the square root and we haven't found + * any smaller prime factors, then the number is prime.*/ + limit = floor(sqrt(num)); - /* Every prime other than 2 and 3 is in the form 6k+1 or 6k-1. - * If I check all those value no prime factors of the number - * will be missed. If a factor is found, the number is not prime - * and the function returns 0.*/ - for(i = 5; i <= limit; i += 6) - { - if(num % i == 0 || num % (i + 2) == 0) - { - return 0; - } - } + /* Every prime other than 2 and 3 is in the form 6k+1 or 6k-1. + * If I check all those value no prime factors of the number + * will be missed. If a factor is found, the number is not prime + * and the function returns 0.*/ + for(i = 5; i <= limit; i += 6) + { + if(num % i == 0 || num % (i + 2) == 0) + { + return 0; + } + } - /* If no factor is found up to the square root of num, num is prime.*/ - return 1; + /* If no factor is found up to the square root of num, num is prime.*/ + return 1; } int is_palindrome(int num, int base) { - int reverse = 0, tmp; + int reverse = 0, tmp; - tmp = num; + tmp = num; - /* Start with reverse=0, get the rightmost digit of the number using - * modulo operation (num modulo base), add it to reverse. Remove the - * rightmost digit from num dividing num by the base, shift the reverse left - * multiplying by the base, repeat until all digits have been inserted - * in reverse order.*/ - while(tmp > 0) - { - reverse *= base; - reverse += tmp % base; - tmp /= base; - } + /* Start with reverse=0, get the rightmost digit of the number using + * modulo operation (num modulo base), add it to reverse. Remove the + * rightmost digit from num dividing num by the base, shift the reverse left + * multiplying by the base, repeat until all digits have been inserted + * in reverse order.*/ + while(tmp > 0) + { + reverse *= base; + reverse += tmp % base; + tmp /= base; + } - /* If the reversed number is equal to the original one, then it's palindrome.*/ - if(num == reverse) - { - return 1; - } + /* If the reversed number is equal to the original one, then it's palindrome.*/ + if(num == reverse) + { + return 1; + } - return 0; + return 0; } /* Same function, using GMP Library for long numbers.*/ int is_palindrome_mpz(mpz_t num, int base) { - mpz_t tmp, reverse, rem; + mpz_t tmp, reverse, rem; - mpz_inits(tmp, reverse, rem, NULL); - mpz_set(tmp, num); - mpz_set_ui(reverse, 0); + mpz_inits(tmp, reverse, rem, NULL); + mpz_set(tmp, num); + mpz_set_ui(reverse, 0); - while(mpz_cmp_ui(tmp, 0) > 0) - { - mpz_mul_ui(reverse, reverse, base); - mpz_tdiv_qr_ui(tmp, rem, tmp, base); - mpz_add(reverse, reverse, rem); - } + while(mpz_cmp_ui(tmp, 0) > 0) + { + mpz_mul_ui(reverse, reverse, base); + mpz_tdiv_qr_ui(tmp, rem, tmp, base); + mpz_add(reverse, reverse, rem); + } - if(!mpz_cmp(num, reverse)) - { - mpz_clears(reverse, rem, NULL); - return 1; - } - - mpz_clears(reverse, rem, NULL); + if(!mpz_cmp(num, reverse)) + { + mpz_clears(reverse, rem, NULL); + return 1; + } - return 0; + mpz_clears(reverse, rem, NULL); + + return 0; } long int gcd(long int a, long int b) { - /* Euclid's algorithm for the greatest common divisor: - * gcd(a, 0) = a - * gcd(a, b) = gcd(b, a modulo b)*/ - if(b == 0) - { - return a; - } + /* Euclid's algorithm for the greatest common divisor: + * gcd(a, 0) = a + * gcd(a, b) = gcd(b, a modulo b)*/ + if(b == 0) + { + return a; + } - return gcd(b, a%b); + return gcd(b, a%b); } /* Least common multiple algorithm using the greatest common divisor.*/ long int lcm(long int a, long int b) { - return a * b / gcd(a, b); + return a * b / gcd(a, b); } /* Recursive function to calculate the least common multiple of more than 2 numbers.*/ long int lcmm(long int *values, int n) { - int i; - long int value; + int i; + long int value; - /* If there are only two numbers, use the lcm function to calculate the lcm.*/ - if(n == 2) - { - return lcm(values[0], values[1]); - } - else - { - value = values[0]; + /* If there are only two numbers, use the lcm function to calculate the lcm.*/ + if(n == 2) + { + return lcm(values[0], values[1]); + } + else + { + value = values[0]; - for(i = 0; i < n - 1; i++) - { - values[i] = values[i+1]; - } + for(i = 0; i < n - 1; i++) + { + values[i] = values[i+1]; + } - /* Recursively calculate lcm(a, b, c, ..., n) = lcm(a, lcm(b, c, ..., n)).*/ - return lcm(value, lcmm(values, n-1)); - } + /* Recursively calculate lcm(a, b, c, ..., n) = lcm(a, lcm(b, c, ..., n)).*/ + return lcm(value, lcmm(values, n-1)); + } } /* Function implementing the Sieve or Eratosthenes to generate * primes up to a certain number.*/ int *sieve(int n) { - int i, j, limit; - int *primes; + int i, j, limit; + int *primes; - if((primes = (int *)malloc(n*sizeof(int))) == NULL) - { - return NULL; - } + if((primes = (int *)malloc(n*sizeof(int))) == NULL) + { + return NULL; + } - /* 0 and 1 are not prime, 2 and 3 are prime.*/ - primes[0] = 0; - primes[1] = 0; - primes[2] = 1; - primes[3] = 1; + /* 0 and 1 are not prime, 2 and 3 are prime.*/ + primes[0] = 0; + primes[1] = 0; + primes[2] = 1; + primes[3] = 1; - /* Cross out (set to 0) all even numbers and set the odd numbers to 1 (possible prime).*/ - for(i = 4; i < n - 1; i += 2) - { - primes[i] = 0; - primes[i+1] = 1; - } + /* Cross out (set to 0) all even numbers and set the odd numbers to 1 (possible prime).*/ + for(i = 4; i < n - 1; i += 2) + { + primes[i] = 0; + primes[i+1] = 1; + } - /* If i is prime, all multiples of i smaller than i*i have already been crossed out. - * if i=sqrt(n), all multiples of i up to n (the target) have been crossed out. So - * there is no need check i>sqrt(n).*/ - limit = floor(sqrt(n)); + /* If i is prime, all multiples of i smaller than i*i have already been crossed out. + * if i=sqrt(n), all multiples of i up to n (the target) have been crossed out. So + * there is no need check i>sqrt(n).*/ + limit = floor(sqrt(n)); - for(i = 3; i <= limit; i += 2) - { - /* Find the next number not crossed out, which is prime.*/ - if(primes[i]) - { - /* Cross out all multiples of i, starting with i*i because any smaller multiple - * of i has a smaller prime factor and has already been crossed out. Also, since - * i is odd, i*i+i is even and has already been crossed out, so multiples are - * crossed out with steps of 2*i.*/ - for(j = i * i; j < n; j += 2 * i) - { - primes[j] = 0; - } - } - } + for(i = 3; i <= limit; i += 2) + { + /* Find the next number not crossed out, which is prime.*/ + if(primes[i]) + { + /* Cross out all multiples of i, starting with i*i because any smaller multiple + * of i has a smaller prime factor and has already been crossed out. Also, since + * i is odd, i*i+i is even and has already been crossed out, so multiples are + * crossed out with steps of 2*i.*/ + for(j = i * i; j < n; j += 2 * i) + { + primes[j] = 0; + } + } + } - return primes; + return primes; } int count_divisors(int n) { - int i, limit, count = 0; + int i, limit, count = 0; - /* For every divisor below the square root of n, there is a corresponding one - * above the square root, so it's sufficient to check up to the square root of n - * and count every divisor twice. If n is a perfect square, the last divisor is - * wrongly counted twice and must be corrected.*/ - limit = floor(sqrt(n)); + /* For every divisor below the square root of n, there is a corresponding one + * above the square root, so it's sufficient to check up to the square root of n + * and count every divisor twice. If n is a perfect square, the last divisor is + * wrongly counted twice and must be corrected.*/ + limit = floor(sqrt(n)); - for(i = 1; i <= limit; i++) - { - if(n % i == 0) - { - count += 2; - } - } - - if(n == limit * limit) - { - count--; - } + for(i = 1; i <= limit; i++) + { + if(n % i == 0) + { + count += 2; + } + } - return count; + if(n == limit * limit) + { + count--; + } + + return count; } int find_max_path(int **triang, int n) { - int i, j; + int i, j; - /* Start from the second to last row and go up.*/ - for(i = n - 2; i >= 0; i--) - { - /* For each element in the row, check the two adjacent elements - * in the row below and sum the larger one to it. At the end, - * the element at the top will contain the value of the maximum path.*/ - for(j = 0; j <= i; j++) - { - if(triang[i+1][j] > triang[i+1][j+1]) - triang[i][j] += triang[i+1][j]; - else - triang[i][j] += triang[i+1][j+1]; - } - } + /* Start from the second to last row and go up.*/ + for(i = n - 2; i >= 0; i--) + { + /* For each element in the row, check the two adjacent elements + * in the row below and sum the larger one to it. At the end, + * the element at the top will contain the value of the maximum path.*/ + for(j = 0; j <= i; j++) + { + if(triang[i+1][j] > triang[i+1][j+1]) + triang[i][j] += triang[i+1][j]; + else + triang[i][j] += triang[i+1][j+1]; + } + } - return triang[0][0]; + return triang[0][0]; } int sum_of_divisors(int n, int proper) { - int i, sum = 1, limit; + int i, sum = 1, limit; - /* For each divisor of n smaller than the square root of n, - * there is another one larger than the square root. If i is - * a divisor of n, so is n/i. Checking divisors i up to square - * root of n and adding both i and n/i is sufficient to sum - * all divisors.*/ - limit = floor(sqrt(n)); + /* For each divisor of n smaller than the square root of n, + * there is another one larger than the square root. If i is + * a divisor of n, so is n/i. Checking divisors i up to square + * root of n and adding both i and n/i is sufficient to sum + * all divisors.*/ + limit = floor(sqrt(n)); - for(i = 2; i <= limit; i++) - { - if(n % i == 0) - { - sum += i; - sum += n / i; - } - } - - /* If n is a perfect square, i=limit is a divisor and - * has to be counted only once.*/ - if(n == limit * limit) - { - sum -= limit; - } + for(i = 2; i <= limit; i++) + { + if(n % i == 0) + { + sum += i; + sum += n / i; + } + } - if(!proper) - { - sum += n; - } + /* If n is a perfect square, i=limit is a divisor and + * has to be counted only once.*/ + if(n == limit * limit) + { + sum -= limit; + } - return sum; + if(!proper) + { + sum += n; + } + + return sum; } void swap(void **array, int i, int j) { - void *tmp; + void *tmp; - tmp = array[i]; - array[i] = array[j]; - array[j] = tmp; + tmp = array[i]; + array[i] = array[j]; + array[j] = tmp; } void insertion_sort(void **array, int l, int r, int (*cmp)(void *lv, void *rv)) { - int i, j; - void *tmp; - - /* After this cycle the smallest element will be in the first position of the array.*/ - for(i = r; i > l; i--) - { - if(cmp(array[i], array[i-1]) < 0) - { - swap(array, i, i-1); - } - } + int i, j; + void *tmp; - /* For each element in the array (starting from i=2), move it to the left until a - * smaller element on its left is found.*/ - for(i = l + 2; i <= r; i++) - { - tmp = array[i]; - j = i; + /* After this cycle the smallest element will be in the first position of the array.*/ + for(i = r; i > l; i--) + { + if(cmp(array[i], array[i-1]) < 0) + { + swap(array, i, i-1); + } + } - while(cmp(tmp, array[j-1]) < 0) - { - array[j] = array[j-1]; - j--; - } - - array[j] = tmp; - } + /* For each element in the array (starting from i=2), move it to the left until a + * smaller element on its left is found.*/ + for(i = l + 2; i <= r; i++) + { + tmp = array[i]; + j = i; + + while(cmp(tmp, array[j-1]) < 0) + { + array[j] = array[j-1]; + j--; + } + + array[j] = tmp; + } } int partition(void **array, int l, int r, int (*cmp)(void *lv, void *rv)) { - int i = l -1, j = r; - void *pivot; - - /* Arbitrarily selecting the rightmost element as pivot.*/ - pivot = array[r]; - - while(1) - { - /* From the left, loop until an element greater than the pivot is found.*/ - while(cmp(array[++i], pivot) < 0); - /* From the right, loop until an element smaller than the pivot is found - * or the beginning of the array is reached.*/ - while(cmp(array[--j], pivot) > 0) - { - if(j == l) - { + int i = l -1, j = r; + void *pivot; + + /* Arbitrarily selecting the rightmost element as pivot.*/ + pivot = array[r]; + + while(1) + { + /* From the left, loop until an element greater than the pivot is found.*/ + while(cmp(array[++i], pivot) < 0); + /* From the right, loop until an element smaller than the pivot is found + * or the beginning of the array is reached.*/ + while(cmp(array[--j], pivot) > 0) + { + if(j == l) + { + break; + } + } + + /* If j<=i, array[j], which is smaller than pivot, is already on the left + * of array[i], which is larger than pivot, so they don't need to be swapped.*/ + if(j <= i) + { break; - } - } + } - /* If j<=i, array[j], which is smaller than pivot, is already on the left - * of array[i], which is larger than pivot, so they don't need to be swapped.*/ - if(j <= i) - { - break; - } + /* If j>i, swap array[i] and array[j].*/ + swap(array, i, j); + } - /* If j>i, swap array[i] and array[j].*/ - swap(array, i, j); - } + /* Swap array[i] with pivot. All elements on the left of pivot are smaller, all + * the elements on the right are bigger, so pivot is in the correct position + * in the sorted array.*/ + swap(array, i, r); - /* Swap array[i] with pivot. All elements on the left of pivot are smaller, all - * the elements on the right are bigger, so pivot is in the correct position - * in the sorted array.*/ - swap(array, i, r); - - return i; + return i; } void quick_sort(void **array, int l, int r, int (*cmp)(void *lv, void *rv)) { - int i; - - /* If the array is small, it's better to just use a simple insertion_sort algorithm.*/ - if(r - l <= 20) - { - insertion_sort(array, l, r, cmp); - return; - } - - /* Partition the array and recursively run quick_sort on the two partitions.*/ - i = partition(array, l, r, cmp); - quick_sort(array, l, i-1, cmp); - quick_sort(array, i+1, r, cmp); + int i; + + /* If the array is small, it's better to just use a simple insertion_sort algorithm.*/ + if(r - l <= 20) + { + insertion_sort(array, l, r, cmp); + return; + } + + /* Partition the array and recursively run quick_sort on the two partitions.*/ + i = partition(array, l, r, cmp); + quick_sort(array, l, i-1, cmp); + quick_sort(array, i+1, r, cmp); } /* Implements SEPA (Simple, Efficient Permutation Algorithm) * to find the next permutation.*/ int next_permutation(void **perm, int n, int (*cmp)(void *a, void *b)) { - int i, key; + int i, key; - /* Starting from the right of the array, for each pair of values - * if the left one is smaller than the right, that value is the key.*/ - for(i = n - 2; i >= 0; i--) - { - if(cmp(perm[i], perm[i+1]) < 0) - { - key = i; - break; - } - } + /* Starting from the right of the array, for each pair of values + * if the left one is smaller than the right, that value is the key.*/ + for(i = n - 2; i >= 0; i--) + { + if(cmp(perm[i], perm[i+1]) < 0) + { + key = i; + break; + } + } - /* If no left value is smaller than its right value, the - * array is in reverse order, i.e. it's the last permutation.*/ - if(i == -1) - { - return -1; - } + /* If no left value is smaller than its right value, the + * array is in reverse order, i.e. it's the last permutation.*/ + if(i == -1) + { + return -1; + } - /* Find the smallest value on the right of the key which is bigger than the key itself, - * considering that the values at the right of the key are in reverse order.*/ - for(i = key + 1; i < n && cmp(perm[i], perm[key]) > 0; i++); + /* Find the smallest value on the right of the key which is bigger than the key itself, + * considering that the values at the right of the key are in reverse order.*/ + for(i = key + 1; i < n && cmp(perm[i], perm[key]) > 0; i++); - /* Swap the value found and the key.*/ - swap(perm, key, i-1); - /* Sort the values at the right of the key. This is - * the next permutation.*/ - insertion_sort(perm, key+1, n-1, cmp); + /* Swap the value found and the key.*/ + swap(perm, key, i-1); + /* Sort the values at the right of the key. This is + * the next permutation.*/ + insertion_sort(perm, key+1, n-1, cmp); - return 0; + return 0; } int is_pandigital(int value, int n) { - int *digits; - int i, digit; + int *digits; + int i, digit; - if((digits = (int *)calloc(n+1, sizeof(int))) == NULL) - { - fprintf(stderr, "Error while allocating memory\n"); - exit(1); - } + if((digits = (int *)calloc(n+1, sizeof(int))) == NULL) + { + fprintf(stderr, "Error while allocating memory\n"); + exit(1); + } - for(i = 0; i < n && value > 0; i++) - { - digit = value % 10; - if(digit > n) - { - return 0; - } - digits[digit]++; - value /= 10; - } + for(i = 0; i < n && value > 0; i++) + { + digit = value % 10; + if(digit > n) + { + return 0; + } + digits[digit]++; + value /= 10; + } - if(i < n || value > 0) - { - free(digits); - return 0; - } + if(i < n || value > 0) + { + free(digits); + return 0; + } - if(digits[0] != 0) - { - free(digits); - return 0; - } + if(digits[0] != 0) + { + free(digits); + return 0; + } - for(i = 1; i <= n; i++) - { - if(digits[i] != 1) - { - free(digits); - return 0; - } - } + for(i = 1; i <= n; i++) + { + if(digits[i] != 1) + { + free(digits); + return 0; + } + } - free(digits); + free(digits); - return 1; + return 1; } int is_pentagonal(long int n) { - double i; + double i; - /* A number n is pentagonal if p=(sqrt(24n+1)+1)/6 is an integer. - * In this case, n is the pth pentagonal number.*/ - i = (sqrt(24*n+1) + 1) / 6; + /* A number n is pentagonal if p=(sqrt(24n+1)+1)/6 is an integer. + * In this case, n is the pth pentagonal number.*/ + i = (sqrt(24*n+1) + 1) / 6; - if(i == (int)i) - { - return 1; - } - else - { - return 0; - } + if(i == (int)i) + { + return 1; + } + else + { + return 0; + } } /* Function implementing the iterative algorithm taken from Wikipedia * to find the continued fraction for sqrt(S). The algorithm is as * follows: - * + * * m_0=0 * d_0=1 * a_0=floor(sqrt(n)) @@ -487,117 +487,117 @@ int is_pentagonal(long int n) * if a_i=2*a_0, the algorithm ends.*/ int *build_sqrt_cont_fraction(int i, int *period, int l) { - int mn = 0, mn1, dn = 1, dn1, a0, an, an1, count = 0, j; - int *fraction; + int mn = 0, mn1, dn = 1, dn1, a0, an, an1, count = 0, j; + int *fraction; - if((fraction = (int *)malloc(l*sizeof(int))) == NULL) - { - return NULL; - } + if((fraction = (int *)malloc(l*sizeof(int))) == NULL) + { + return NULL; + } - j = 0; - a0 = floor(sqrt(i)); - an = a0; - fraction[j] = an; - j++; + j = 0; + a0 = floor(sqrt(i)); + an = a0; + fraction[j] = an; + j++; - do - { - mn1 = dn * an - mn; - dn1 = (i - mn1 * mn1)/ dn; - an1 = floor((a0+mn1)/dn1); - mn = mn1; - dn = dn1; - an = an1; - count++; - fraction[j] = an; - j++; - }while(an != 2 * a0); + do + { + mn1 = dn * an - mn; + dn1 = (i - mn1 * mn1)/ dn; + an1 = floor((a0+mn1)/dn1); + mn = mn1; + dn = dn1; + an = an1; + count++; + fraction[j] = an; + j++; + } while(an != 2 * a0); - fraction[j] = -1; + fraction[j] = -1; - *period = count; + *period = count; - return fraction; + return fraction; } /* Function to solve the Diophantine equation in the form x^2-Dy^2=1 * (Pell equation) using continued fractions.*/ int pell_eq(int d, mpz_t x) { - int found = 0, j, period; - mpz_t n1, n2, n3, d1, d2, d3, sol, tmp; - int *fraction; + int found = 0, j, period; + mpz_t n1, n2, n3, d1, d2, d3, sol, tmp; + int *fraction; - /* Find the continued fraction for sqrt(d).*/ - if((fraction = build_sqrt_cont_fraction(d, &period, 100)) == NULL) - { - return -1; - } + /* Find the continued fraction for sqrt(d).*/ + if((fraction = build_sqrt_cont_fraction(d, &period, 100)) == NULL) + { + return -1; + } - /* Calculate the first convergent of the continued fraction.*/ - mpz_init_set_ui(n1, 0); - mpz_init_set_ui(n2, 1); - mpz_init_set_ui(d1, 1); - mpz_init_set_ui(d2, 0); - mpz_inits(n3, d3, sol, tmp, NULL); + /* Calculate the first convergent of the continued fraction.*/ + mpz_init_set_ui(n1, 0); + mpz_init_set_ui(n2, 1); + mpz_init_set_ui(d1, 1); + mpz_init_set_ui(d2, 0); + mpz_inits(n3, d3, sol, tmp, NULL); - j = 0; - mpz_mul_ui(n3, n2, fraction[j]); - mpz_add(n3, n3, n1); - mpz_mul_ui(d3, d2, fraction[j]); - mpz_add(d3, d3, d1); - j++; + j = 0; + mpz_mul_ui(n3, n2, fraction[j]); + mpz_add(n3, n3, n1); + mpz_mul_ui(d3, d2, fraction[j]); + mpz_add(d3, d3, d1); + j++; - /* Check if x=n, y=d solve the equation x^2-Dy^2=1.*/ - mpz_mul(sol, n3, n3); - mpz_mul(tmp, d3, d3); - mpz_mul_ui(tmp, tmp, d); - mpz_sub(sol, sol, tmp); + /* Check if x=n, y=d solve the equation x^2-Dy^2=1.*/ + mpz_mul(sol, n3, n3); + mpz_mul(tmp, d3, d3); + mpz_mul_ui(tmp, tmp, d); + mpz_sub(sol, sol, tmp); - if(mpz_cmp_ui(sol, 1) == 0) - { - mpz_set(x, n3); - found = 1; - free(fraction); - mpz_clears(n1, n2, n3, d1, d2, d3, sol, tmp, NULL); - } + if(mpz_cmp_ui(sol, 1) == 0) + { + mpz_set(x, n3); + found = 1; + free(fraction); + mpz_clears(n1, n2, n3, d1, d2, d3, sol, tmp, NULL); + } - /* Until a solution is found, calculate the next convergent - * and check if x=n and y=d solve the equation.*/ - while(!found) - { - mpz_set(n1, n2); - mpz_set(n2, n3); - mpz_set(d1, d2); - mpz_set(d2, d3); - mpz_mul_ui(n3, n2, fraction[j]); - mpz_add(n3, n3, n1); - mpz_mul_ui(d3, d2, fraction[j]); - mpz_add(d3, d3, d1); + /* Until a solution is found, calculate the next convergent + * and check if x=n and y=d solve the equation.*/ + while(!found) + { + mpz_set(n1, n2); + mpz_set(n2, n3); + mpz_set(d1, d2); + mpz_set(d2, d3); + mpz_mul_ui(n3, n2, fraction[j]); + mpz_add(n3, n3, n1); + mpz_mul_ui(d3, d2, fraction[j]); + mpz_add(d3, d3, d1); - mpz_mul(sol, n3, n3); - mpz_mul(tmp, d3, d3); - mpz_mul_ui(tmp, tmp, d); - mpz_sub(sol, sol, tmp); + mpz_mul(sol, n3, n3); + mpz_mul(tmp, d3, d3); + mpz_mul_ui(tmp, tmp, d); + mpz_sub(sol, sol, tmp); - if(mpz_cmp_ui(sol, 1) == 0) - { - mpz_set(x, n3); - found = 1; - free(fraction); - mpz_clears(n1, n2, n3, d1, d2, d3, sol, tmp, NULL); - } + if(mpz_cmp_ui(sol, 1) == 0) + { + mpz_set(x, n3); + found = 1; + free(fraction); + mpz_clears(n1, n2, n3, d1, d2, d3, sol, tmp, NULL); + } - j++; + j++; - if(fraction[j] == -1) - { - j = 1; - } - } + if(fraction[j] == -1) + { + j = 1; + } + } - return 0; + return 0; } /* Function to check if a number is semiprime. Parameters include @@ -605,97 +605,97 @@ int pell_eq(int d, mpz_t x) * primes.*/ int is_semiprime(int n, int *p, int *q, int *primes) { - int i, limit; + int i, limit; - /* If n is prime, it's not semiprime.*/ - if(primes[n]) - { - return 0; - } + /* If n is prime, it's not semiprime.*/ + if(primes[n]) + { + return 0; + } - /* Check if n is semiprime and one of the factors is 2.*/ - if(n % 2 == 0) - { - if(primes[n/2]) - { - *p = 2; - *q = n / 2; - return 1; - } - else - { - return 0; - } - } - /* Check if n is semiprime and one of the factors is 3.*/ - else if(n % 3 == 0) - { - if(primes[n/3]) - { - *p = 3; - *q = n / 3; - return 1; - } - else - { - return 0; - } - } - - /*Any number can have only one prime factor greater than its - square root, so we can stop checking at this point.*/ - limit = floor(sqrt(n)); - - /* Every prime other than 2 and 3 is in the form 6k+1 or 6k-1. - * If I check all those value no prime factors of the number - * will be missed. For each of these possible primes, check if - * they are prime, then if the number is semiprime with using - * that factor.*/ - for(i = 5; i <= limit; i += 6) - { - if(primes[i] && n % i == 0) - { - if(primes[n/i]) - { - *p = i; - *q = n / i; + /* Check if n is semiprime and one of the factors is 2.*/ + if(n % 2 == 0) + { + if(primes[n/2]) + { + *p = 2; + *q = n / 2; return 1; - } - else - { + } + else + { return 0; - } - } - else if(primes[i+2] && n % (i + 2) == 0) - { - if(primes[n/(i+2)]) - { - *p = i + 2; - *q = n / (i + 2); + } + } + /* Check if n is semiprime and one of the factors is 3.*/ + else if(n % 3 == 0) + { + if(primes[n/3]) + { + *p = 3; + *q = n / 3; return 1; - } - else - { + } + else + { return 0; - } - } - } + } + } - return 0; + /*Any number can have only one prime factor greater than its + square root, so we can stop checking at this point.*/ + limit = floor(sqrt(n)); + + /* Every prime other than 2 and 3 is in the form 6k+1 or 6k-1. + * If I check all those value no prime factors of the number + * will be missed. For each of these possible primes, check if + * they are prime, then if the number is semiprime with using + * that factor.*/ + for(i = 5; i <= limit; i += 6) + { + if(primes[i] && n % i == 0) + { + if(primes[n/i]) + { + *p = i; + *q = n / i; + return 1; + } + else + { + return 0; + } + } + else if(primes[i+2] && n % (i + 2) == 0) + { + if(primes[n/(i+2)]) + { + *p = i + 2; + *q = n / (i + 2); + return 1; + } + else + { + return 0; + } + } + } + + return 0; } /* If n=pq is semiprime, phi(n)=(p-1)(q-1)=pq-p-q+1=n-(p+4)+1 * if p!=q. If p=q (n is a square), phi(n)=n-p.*/ int phi_semiprime(int n, int p, int q) { - if(p == q) - { - return n - p; - } - else - { - return n - (p + q) + 1; - } + if(p == q) + { + return n - p; + } + else + { + return n - (p + q) + 1; + } } /* Function to calculate phi(n) for any n. If n is prime, phi(n)=n-1, @@ -703,145 +703,145 @@ int phi_semiprime(int n, int p, int q) * phi(n)=n*prod(1-1/p) for every distinct prime p that divides n.*/ int phi(int n, int *primes) { - int i, p, q, limit; - double ph = (double)n; + int i, p, q, limit; + double ph = (double)n; - /* If n is prime, phi(n)=n-1*/ - if(primes[n]) - { - return n - 1; - } + /* If n is prime, phi(n)=n-1*/ + if(primes[n]) + { + return n - 1; + } - /* If n is semiprime, use above function.*/ - if(is_semiprime(n, &p, &q, primes)) - { - return phi_semiprime(n, p, q); - } + /* If n is semiprime, use above function.*/ + if(is_semiprime(n, &p, &q, primes)) + { + return phi_semiprime(n, p, q); + } - /* If 2 is a factor of n, multiply the current ph (which now is n) - * by 1-1/2, then divide all factors 2.*/ - if(n % 2 == 0) - { - ph *= (1.0 - 1.0 / 2.0); + /* If 2 is a factor of n, multiply the current ph (which now is n) + * by 1-1/2, then divide all factors 2.*/ + if(n % 2 == 0) + { + ph *= (1.0 - 1.0 / 2.0); - do - { - n /= 2; - }while(n % 2 == 0); - } + do + { + n /= 2; + } while(n % 2 == 0); + } - /* If 3 is a factor of n, multiply the current ph by 1-1/3, - * then divide all factors 3.*/ - if(n % 3 == 0) - { - ph *= (1.0 - 1.0 / 3.0); + /* If 3 is a factor of n, multiply the current ph by 1-1/3, + * then divide all factors 3.*/ + if(n % 3 == 0) + { + ph *= (1.0 - 1.0 / 3.0); - do - { - n /= 3; - }while(n % 3 == 0); - } + do + { + n /= 3; + } while(n % 3 == 0); + } - /*Any number can have only one prime factor greater than its - * square root, so we can stop checking at this point and deal - * with the only factor larger than sqrt(n), if present, at the end.*/ - limit = floor(sqrt(n)); + /*Any number can have only one prime factor greater than its + * square root, so we can stop checking at this point and deal + * with the only factor larger than sqrt(n), if present, at the end.*/ + limit = floor(sqrt(n)); - /* Every prime other than 2 and 3 is in the form 6k+1 or 6k-1. - * If I check all those value no prime factors of the number - * will be missed. For each of these possible primes, check if - * they are prime, then check if the number divides n, in which - * case update the current ph.*/ - for(i = 5; i <= limit; i += 6) - { - if(primes[i]) - { - if(n % i == 0) - { - ph *= (1.0 - 1.0 / i); - - do + /* Every prime other than 2 and 3 is in the form 6k+1 or 6k-1. + * If I check all those value no prime factors of the number + * will be missed. For each of these possible primes, check if + * they are prime, then check if the number divides n, in which + * case update the current ph.*/ + for(i = 5; i <= limit; i += 6) + { + if(primes[i]) + { + if(n % i == 0) { - n /= i; - }while(n % i == 0); - } - } - if(primes[i+2]) - { - if(n % (i + 2) == 0) - { - ph *= (1.0 - 1.0 /(i + 2)); + ph *= (1.0 - 1.0 / i); - do + do + { + n /= i; + } while(n % i == 0); + } + } + if(primes[i+2]) + { + if(n % (i + 2) == 0) { - n /= (i + 2); - }while(n % (i + 2) == 0); - } - } - } + ph *= (1.0 - 1.0 /(i + 2)); - /* After dividing all prime factors smaller than sqrt(n), n is either 1 - * or is equal to the only prime factor greater than sqrt(n). In this - * second case, we need to update ph with the last prime factor.*/ - if(n > 1) - { - ph *= (1.0 - 1.0 / n); - } + do + { + n /= (i + 2); + } while(n % (i + 2) == 0); + } + } + } - return (int)ph; + /* After dividing all prime factors smaller than sqrt(n), n is either 1 + * or is equal to the only prime factor greater than sqrt(n). In this + * second case, we need to update ph with the last prime factor.*/ + if(n > 1) + { + ph *= (1.0 - 1.0 / n); + } + + return (int)ph; } /* Function implementing the partition function.*/ long int partition_fn(int n, long int *partitions, int mod) { - int k, limit; - long int res = 0; + int k, limit; + long int res = 0; - /* The partition function for negative numbers is 0 by definition.*/ - if(n < 0) - { - return 0; - } + /* The partition function for negative numbers is 0 by definition.*/ + if(n < 0) + { + return 0; + } - /* The partition function for zero is 1 by definition.*/ - if(n == 0) - { - partitions[n] = 1; + /* The partition function for zero is 1 by definition.*/ + if(n == 0) + { + partitions[n] = 1; - return 1; - } + return 1; + } - /* If the partition for the current n has already been calculated, return the value.*/ - if(partitions[n] != 0) - { - return partitions[n]; - } + /* If the partition for the current n has already been calculated, return the value.*/ + if(partitions[n] != 0) + { + return partitions[n]; + } - k = -ceil((sqrt(24*n+1)-1)/6); - limit = floor((sqrt(24*n+1)+1)/6); + k = -ceil((sqrt(24*n+1)-1)/6); + limit = floor((sqrt(24*n+1)+1)/6); - while(k <= limit) - { - if(k != 0) - { - res += pow(-1, k+1) * partition_fn(n-k*(3*k-1)/2, partitions, mod); - } - k++; - } + while(k <= limit) + { + if(k != 0) + { + res += pow(-1, k+1) * partition_fn(n-k*(3*k-1)/2, partitions, mod); + } + k++; + } - /* Give the result modulo mod, if mod=!-1, otherwise give the full result.*/ - if(mod != -1) - { - partitions[n] = res % mod; + /* Give the result modulo mod, if mod=!-1, otherwise give the full result.*/ + if(mod != -1) + { + partitions[n] = res % mod; - return res % mod; - } - else - { - partitions[n] = res; + return res % mod; + } + else + { + partitions[n] = res; - return res; - } + return res; + } } /* Function implementing Dijkstra's algorithm for a mxn matrix, where the matrix represents @@ -851,137 +851,137 @@ long int partition_fn(int n, long int *partitions, int mod) * instead of only down and forward, and the starting row.*/ int dijkstra(int **matrix, int **distances, int m, int n, int up, int back, int start) { - int i, j, min_i, min_j, min; - int **visited; + int i, j, min_i, min_j, min; + int **visited; - if((visited = (int **)malloc(m*sizeof(int *))) == NULL) - { - return -1; - } + if((visited = (int **)malloc(m*sizeof(int *))) == NULL) + { + return -1; + } - for(i = 0; i < m; i++) - { - if((visited[i] = (int *)calloc(n, sizeof(int))) == NULL) - { - return -1; - } - } + for(i = 0; i < m; i++) + { + if((visited[i] = (int *)calloc(n, sizeof(int))) == NULL) + { + return -1; + } + } - /* Set the current distances to the maximum value.*/ - for(i = 0; i < m; i++) - { - for(j = 0; j < n; j++) - { - distances[i][j] = INT_MAX; - } - } + /* Set the current distances to the maximum value.*/ + for(i = 0; i < m; i++) + { + for(j = 0; j < n; j++) + { + distances[i][j] = INT_MAX; + } + } - /* Set the distance of the starting node to its value.*/ - i = start; - j = 0; - distances[i][j] = matrix[i][j]; + /* Set the distance of the starting node to its value.*/ + i = start; + j = 0; + distances[i][j] = matrix[i][j]; - do - { - /* Visit the first node, and update the distance of its 2, 3 or 4 - * adjacent nodes.*/ - visited[i][j] = 1; + do + { + /* Visit the first node, and update the distance of its 2, 3 or 4 + * adjacent nodes.*/ + visited[i][j] = 1; - if(i < m - 1 && distances[i][j] + matrix[i+1][j] < distances[i+1][j]) - { - distances[i+1][j] = distances[i][j] + matrix[i+1][j]; - } + if(i < m - 1 && distances[i][j] + matrix[i+1][j] < distances[i+1][j]) + { + distances[i+1][j] = distances[i][j] + matrix[i+1][j]; + } - if(up) - { - if(i > 0 && distances[i][j] + matrix[i-1][j] < distances[i-1][j]) - { - distances[i-1][j] = distances[i][j] + matrix[i-1][j]; - } - } - - if(j < n -1 && distances[i][j] + matrix[i][j+1] < distances[i][j+1]) - { - distances[i][j+1] = distances[i][j] + matrix[i][j+1]; - } - - if(back) - { - if(j > 0 && distances[i][j] + matrix[i][j-1] < distances[i][j-1]) - { - distances[i][j-1] = distances[i][j] + matrix[i][j-1]; - - } - } - - min = INT_MAX; - - /* Find the non visited node with the current minimum distance.*/ - for(i = 0; i < m; i++) - { - for(j = 0; j < n; j++) - { - if(!visited[i][j] && distances[i][j] <= min) + if(up) + { + if(i > 0 && distances[i][j] + matrix[i-1][j] < distances[i-1][j]) { - min = distances[i][j]; - min_i = i; - min_j = j; + distances[i-1][j] = distances[i][j] + matrix[i-1][j]; } - } - } + } - i = min_i; - j = min_j; - /* Repeat until all nodes have been visited.*/ - }while(i != m - 1 || j != n - 1); + if(j < n -1 && distances[i][j] + matrix[i][j+1] < distances[i][j+1]) + { + distances[i][j+1] = distances[i][j] + matrix[i][j+1]; + } - return 1; + if(back) + { + if(j > 0 && distances[i][j] + matrix[i][j-1] < distances[i][j-1]) + { + distances[i][j-1] = distances[i][j] + matrix[i][j-1]; + + } + } + + min = INT_MAX; + + /* Find the non visited node with the current minimum distance.*/ + for(i = 0; i < m; i++) + { + for(j = 0; j < n; j++) + { + if(!visited[i][j] && distances[i][j] <= min) + { + min = distances[i][j]; + min_i = i; + min_j = j; + } + } + } + + i = min_i; + j = min_j; + /* Repeat until all nodes have been visited.*/ + } while(i != m - 1 || j != n - 1); + + return 1; } /* Function that calculates the radical of n, i.e. the product * of its distinct prime factors.*/ int radical(int n, int *primes) { - int i, limit, rad = 1; + int i, limit, rad = 1; - /* There can be only one prime factor of n greater than sqrt(n), - * if we check up to sqrt(n) and divide all the prime factors we find, - * at the end we will have 1 or the only prime factor larger than sqrt(n).*/ - limit = floor(sqrt(n)); + /* There can be only one prime factor of n greater than sqrt(n), + * if we check up to sqrt(n) and divide all the prime factors we find, + * at the end we will have 1 or the only prime factor larger than sqrt(n).*/ + limit = floor(sqrt(n)); - /* Check if n is divisible by two, and divide all 2s factors. Since 2 - * is the only even prime, we can then loop only on odd numbers.*/ - if(n % 2 == 0) - { - rad *= 2; + /* Check if n is divisible by two, and divide all 2s factors. Since 2 + * is the only even prime, we can then loop only on odd numbers.*/ + if(n % 2 == 0) + { + rad *= 2; - do - { - n /= 2; - }while(n % 2 == 0); - } + do + { + n /= 2; + } while(n % 2 == 0); + } - /* For each prime i, check if it's a factor of n, then divide n by i - * until n % i != 0.*/ - for(i = 3; i <= limit; i+=2) - { - if(primes[i] && n % i == 0) - { - rad *= i; + /* For each prime i, check if it's a factor of n, then divide n by i + * until n % i != 0.*/ + for(i = 3; i <= limit; i+=2) + { + if(primes[i] && n % i == 0) + { + rad *= i; - do - { - n /= i; - }while(n % i == 0); - } + do + { + n /= i; + } while(n % i == 0); + } - /* If n is prime, all other prime factors have been found.*/ - if(n == 1 || primes[n]) - { - rad *= n; - break; - } - } + /* If n is prime, all other prime factors have been found.*/ + if(n == 1 || primes[n]) + { + rad *= n; + break; + } + } - return rad; + return rad; }