Created
August 30, 2024 04:07
-
-
Save jaredkrinke/c5a912e2e2a0f23f009aa30120399840 to your computer and use it in GitHub Desktop.
Project Euler problem 56, in C (to compare against G-Pascal)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Project Euler problem 56, in C (to compare against G-Pascal) | |
| #include <stdio.h> | |
| #define DIGITS 200 | |
| unsigned char a[DIGITS]; | |
| unsigned char m[DIGITS]; | |
| unsigned char m2[DIGITS]; | |
| void numclear(unsigned char *n) { | |
| unsigned char i; | |
| for (i = 0; i < DIGITS; i++) { | |
| n[i] = 0; | |
| } | |
| } | |
| void numacc(unsigned char* n, unsigned char i, unsigned char carry) { | |
| for (; carry > 0; i++) { | |
| carry += n[i]; | |
| n[i] = carry % 10; | |
| carry /= 10; | |
| } | |
| } | |
| void nummult(unsigned char *a, unsigned char* b, unsigned char *r) { | |
| unsigned char i, j; | |
| numclear(r); | |
| for (i = 0; i < 2; i++) { | |
| if (a[i] > 0) { | |
| for (j = 0; j < DIGITS; j++) { | |
| if (b[j] > 0) { | |
| numacc(r, i + j, a[i] * b[j]); | |
| } | |
| } | |
| } | |
| } | |
| } | |
| int numsum(unsigned char *n) { | |
| int result = 0; | |
| unsigned char i; | |
| for (i = 0; i < DIGITS; i++) { | |
| result += n[i]; | |
| } | |
| return result; | |
| } | |
| int findbest(unsigned char max) { | |
| unsigned char *pa = &a[0]; | |
| unsigned char *pm = &m[0]; | |
| unsigned char *pm2 = &m2[0]; | |
| unsigned char *tmp; | |
| int best = 0; | |
| int current; | |
| unsigned char i, j; | |
| numclear(a); | |
| numacc(pa, 0, 1); | |
| for (i = 2; i <= max; i++) { | |
| numacc(pa, 0, 1); | |
| numclear(pm); | |
| numacc(pm, 0, 1); | |
| for (j = 1; j <= max; j++) { | |
| nummult(pa, pm, pm2); | |
| tmp = pm2; | |
| pm2 = pm; | |
| pm = tmp; | |
| current = numsum(pm); | |
| printf("%d^%d:%d ", i, j, current); | |
| if (current > best) { | |
| best = current; | |
| } | |
| } | |
| } | |
| return best; | |
| } | |
| int main() { | |
| printf("\n%d\n", findbest(99)); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment