From b25076fb8c4b23661e8a5473f16224aa89e1b006 Mon Sep 17 00:00:00 2001 From: Aman Raj Date: Tue, 1 Oct 2019 19:51:55 +0530 Subject: [PATCH] Project Euler Solution --- project_euler/Problem 04/sol.c | 31 +++++++++++++++++++++++++++++++ project_euler/Problem 05/sol.c | 30 ++++++++++++++++++++++++++++++ project_euler/Problem 06/sol.c | 12 ++++++++++++ project_euler/Problem 07/sol.c | 27 +++++++++++++++++++++++++++ 4 files changed, 100 insertions(+) create mode 100644 project_euler/Problem 04/sol.c create mode 100644 project_euler/Problem 05/sol.c create mode 100644 project_euler/Problem 06/sol.c create mode 100644 project_euler/Problem 07/sol.c diff --git a/project_euler/Problem 04/sol.c b/project_euler/Problem 04/sol.c new file mode 100644 index 00000000..0a6b4c33 --- /dev/null +++ b/project_euler/Problem 04/sol.c @@ -0,0 +1,31 @@ +#include + +int is_palindromic(unsigned int n) +{ + unsigned int reversed = 0, t = n; + + while (t>0) + { + reversed = 10 * reversed + (t % 10); + t /= 10; + } + return reversed == n; +} + +int main(void) +{ + unsigned int i, j, max = 0; + for (i = 100; i <= 999; i++) + { + for (j = 100; j <= 999; j++) + { + unsigned int p = i * j; + if (is_palindromic(p) && p > max) + { + max = p; + } + } + } + printf("%u\n", max); + return 0; +} diff --git a/project_euler/Problem 05/sol.c b/project_euler/Problem 05/sol.c new file mode 100644 index 00000000..12599033 --- /dev/null +++ b/project_euler/Problem 05/sol.c @@ -0,0 +1,30 @@ +#include + +unsigned long gcd(unsigned long a, unsigned long b) { + unsigned long r; + if (a > b) { + unsigned long t = a; + a = b; + b = t; + } + while (r = a % b) { + a = b; + b = r; + } + return b; +} + +unsigned long lcm(unsigned long a, unsigned long b) { + unsigned long long p = (unsigned long long)a * b; + return p / gcd(a, b); +} + +int main(void) { + unsigned long ans = 1; + unsigned long i; + for (i = 1; i <= 20; i++) { + ans = lcm(ans, i); + } + printf("%lu\n", ans); + return 0; +} diff --git a/project_euler/Problem 06/sol.c b/project_euler/Problem 06/sol.c new file mode 100644 index 00000000..1c7f7dd2 --- /dev/null +++ b/project_euler/Problem 06/sol.c @@ -0,0 +1,12 @@ +#include + +int main(void) { + unsigned s1 = 0, s2 = 0, i; + for (i = 1; i <= 100; i++) { + s1 += i * i; + s2 += i; + } + unsigned ans = s2 * s2 - s1; + printf("%u\n", ans); + return 0; +} diff --git a/project_euler/Problem 07/sol.c b/project_euler/Problem 07/sol.c new file mode 100644 index 00000000..e7dcae2c --- /dev/null +++ b/project_euler/Problem 07/sol.c @@ -0,0 +1,27 @@ +#include +#include + +int main(void) { + char *sieve; + size_t i; + unsigned count = 0; + size_t n = 1000000; + const unsigned target = 10001; + + sieve = calloc(n, sizeof *sieve); + for (i = 2; i < n; i++) { + if (!sieve[i]) { + size_t j; + count++; + if (count == target) { + printf("%lu\n", i); + break; + } + for (j = i * 2; j < n; j += i) { + sieve[j] = 1; + } + } + } + free(sieve); + return 0; +}