From 079938ea7c142b99f1e48dc9ebfb418fc3d40f03 Mon Sep 17 00:00:00 2001 From: Krishna Vedala Date: Mon, 30 Mar 2020 15:43:16 -0400 Subject: [PATCH 1/2] algorithm from http://www.cplusplus.com/forum/beginner/68694/ --- project_euler/Problem 16/sol1.c | 55 +++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 project_euler/Problem 16/sol1.c diff --git a/project_euler/Problem 16/sol1.c b/project_euler/Problem 16/sol1.c new file mode 100644 index 00000000..6c307a40 --- /dev/null +++ b/project_euler/Problem 16/sol1.c @@ -0,0 +1,55 @@ +#include +#include +#include +#include + +int main(int argc, char **argv) +{ + const double tmp = log(10) / log(2); /* required to get number of digits */ + unsigned long MAX_NUM_DIGITS; + uint8_t *digits = NULL; /* array to store individual digits. index 0 = units place */ + int N = 1000, sum = 0; + + if (argc == 2) + N = atoi(argv[1]); + + MAX_NUM_DIGITS = (N + tmp) / tmp; + + digits = calloc(MAX_NUM_DIGITS, sizeof(uint8_t)); + digits[0] = 1; + + if (!digits) + { + perror("Unable to allocate memory!"); + return -1; + } + + for (int i = 0; i < N; i++) + { + int carry = 0; + for (int j = 0; j < MAX_NUM_DIGITS; j++) + { + digits[j] = (digits[j] << 1) + carry; /* digit * 2 + carry */ + // printf("\t value: %d\t", digits[j]); + if (digits[j] > 9) + { + carry = 1; + digits[j] -= 10; + } else + carry = 0; + // printf("carry: %d\t value: %d\n", carry, digits[j]); + + /* accumulate sum for last multiplication */ + if (i == N - 1) + sum += digits[j]; + } + } + + printf("2^%d = ", N); + for(int i = MAX_NUM_DIGITS - 1; i >= 0; i--) + putchar(digits[i] + 0x30); + printf("\n\t Sum: %d\t Num. digits: %lu\n", sum, MAX_NUM_DIGITS); + + free(digits); + return 0; +} \ No newline at end of file From 9f25309c90d6f74fece243a3d4ef598ecd74bc8b Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Mon, 30 Mar 2020 19:43:54 +0000 Subject: [PATCH 2/2] updating DIRECTORY.md --- DIRECTORY.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 5ef05421..ba42ac0e 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -223,6 +223,8 @@ * [Sol](https://github.com/TheAlgorithms/C/blob/master/project_euler/Problem%2006/sol.c) * Problem 07 * [Sol](https://github.com/TheAlgorithms/C/blob/master/project_euler/Problem%2007/sol.c) + * Problem 16 + * [Sol1](https://github.com/TheAlgorithms/C/blob/master/project_euler/Problem%2016/sol1.c) ## Searching * [Binary Search](https://github.com/TheAlgorithms/C/blob/master/searching/Binary_Search.c)