Skip to content

Instantly share code, notes, and snippets.

@haruyama
Last active Aug 29, 2015
Embed
What would you like to do?
lychrel number
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <gmp.h>
bool check_symmetry(mpz_t i)
{
char* s = mpz_get_str(NULL, 10, i);
size_t len = strlen(s);
for (size_t j = 0; j < len / 2 ; ++j) {
if (s[j] != s[len - j - 1]) {
free(s);
return false;
}
}
free(s);
return true;
}
char *strrev(char *str)
{
char *p1, *p2;
if (! str || ! *str)
return str;
for (p1 = str, p2 = str + strlen(str) - 1; p2 > p1; ++p1, --p2)
{
*p1 ^= *p2;
*p2 ^= *p1;
*p1 ^= *p2;
}
return str;
}
void reverse(mpz_t r, mpz_t i)
{
char* rs = strrev(mpz_get_str(NULL, 10, i));
mpz_set_str(r, rs, 10);
free(rs);
}
int main (int argc, char **argv)
{
mpz_t i;
if (argc != 2)
{
printf ("Usage: %s <number>\n", argv[0]);
return EXIT_FAILURE;
}
mpz_init_set_str(i, argv[1], 10);
mpz_t r;
mpz_init(r);
int c = 1;
for (;;) {
if (c % 1000 == 0) {
printf("%d\n", c);
}
if (check_symmetry(i)) {
gmp_printf ("%Zd\n", i);
return EXIT_SUCCESS;
}
reverse(r, i);
mpz_add(i, i, r);
++c;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment