euler/other/e030.c

82 lines
1.6 KiB
C

#include <stdlib.h>
#include <stdio.h>
#include <inttypes.h>
#include <stdbool.h>
#define DIGITS (6)
#define BASE_TEN (100000)
uint32_t* get_digits(uint32_t n) {
uint32_t* r = malloc(sizeof(uint32_t) * DIGITS);
uint32_t base = BASE_TEN;
for (size_t i = 0; i < DIGITS; i++) {
r[i] = n / base;
n = n % base;
base /= 10;
}
return r;
}
uint32_t* get_power_four_lookup() {
uint32_t* r = malloc(sizeof(uint32_t) * 10);
r[0] = 0;
r[1] = 1;
r[2] = 2 * 2 * 2 * 2;
r[3] = 3 * 3 * 3 * 3;
r[4] = 4 * 4 * 4 * 4;
r[5] = 5 * 5 * 5 * 5;
r[6] = 6 * 6 * 6 * 6;
r[7] = 7 * 7 * 7 * 7;
r[8] = 8 * 8 * 8 * 8;
r[9] = 9 * 9 * 9 * 9;
return r;
}
uint32_t* get_power_five_lookup() {
uint32_t* r = malloc(sizeof(uint32_t) * 10);
r[0] = 0;
r[1] = 1;
r[2] = 2 * 2 * 2 * 2 * 2;
r[3] = 3 * 3 * 3 * 3 * 3;
r[4] = 4 * 4 * 4 * 4 * 4;
r[5] = 5 * 5 * 5 * 5 * 5;
r[6] = 6 * 6 * 6 * 6 * 6;
r[7] = 7 * 7 * 7 * 7 * 7;
r[8] = 8 * 8 * 8 * 8 * 8;
r[9] = 9 * 9 * 9 * 9 * 9;
return r;
}
bool is_representable(uint32_t number, uint32_t* lookup) {
uint32_t* digits = get_digits(number);
uint32_t digit_sum = 0;
for (size_t i = 0; i < DIGITS; i++)
digit_sum += lookup[digits[i]];
free(digits);
if (number == digit_sum)
return true;
return false;
}
void print_digits(uint32_t* digits) {
for (size_t i = 0; i < DIGITS; i++) {
printf("%u", digits[i]);
}
}
int main(int argn, char** argv) {
uint32_t* lookup = get_power_five_lookup();
uint32_t sum = 0;
for (uint32_t n = 10; n < 300000; n++)
if (is_representable(n, lookup)) {
printf("%u\n", n);
sum += n;
}
printf("Sum: %d\n", sum);
free(lookup);
return 0;
}