Skip to content

Instantly share code, notes, and snippets.

@jgrar
Created August 4, 2012 03:49
Show Gist options
  • Save jgrar/3254182 to your computer and use it in GitHub Desktop.
Save jgrar/3254182 to your computer and use it in GitHub Desktop.
project euler 20 solution
/* cc -of f.c -lgmp */
#include <stdlib.h>
#include <stdio.h>
#include <gmp.h>
void factorize (mpz_t r, mpz_t n)
{
mpz_t x;
mpz_init_set_ui(x, 1);
mpz_set_ui(r, 1);
while (mpz_cmp(x, n))
{
mpz_mul(r, x, r);
mpz_add_ui(x, x, 1);
}
}
void sumdigits (mpz_t r, mpz_t x)
{
char *s, *p, c;
gmp_asprintf(&s, "%Zu", x);
mpz_set_ui(r, 0);
for (p = s; (c = *p); p++)
{
mpz_add_ui(r, r, c - '0');
}
free(s);
}
int main (int argc, char *argv[])
{
int i;
mpz_t n;
mpz_t f;
mpz_t s;
mpz_init(n);
mpz_init(f);
mpz_init(s);
for (i = 1; i < argc; i++)
{
mpz_set_str(n, argv[i], 10);
factorize(f, n);
sumdigits(s, f);
gmp_printf("%s! = %Zu\tdigit sum = %Zu\n" , argv[i], f, s);
}
mpz_clear(n);
mpz_clear(f);
mpz_clear(s);
exit( (i > 1) ? EXIT_SUCCESS: EXIT_FAILURE );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment