Skip to content

Instantly share code, notes, and snippets.

@paranormal
Created June 16, 2015 23:32
Show Gist options
  • Save paranormal/7d302951f8bed49421a3 to your computer and use it in GitHub Desktop.
Save paranormal/7d302951f8bed49421a3 to your computer and use it in GitHub Desktop.
palindromic calculation
//
// A palindromic number reads the same both ways. The largest palindrome
// made from the product of two 2-digit numbers is 9009 = 91 х 99.
//
// Find the largest palindrome made from the product of two 3-digit numbers.
//
#include <stdio.h>
#include <stdlib.h>
#include <math.h> // !!! don't forget to link against math library: -lm !!!
// ok, seems I need this function now()
// although it would be more «obvious» to do this working with number as a
// string let's do numbers
int is_palindrome(size_t number) {
#define DIGIT(number, power) ((size_t) number / ((size_t) pow(10, power))) % 10
// figuring out digits numbers in the number
ssize_t first = 0, last = 0, digits = 0;
for (ssize_t d = number; d > 1E+1; d *= 1E-1) {
digits++;
}
// also, not the best way to do this, it works twice!!!
for (first = digits, last = 0; first != -1; first -= 1, last += 1) {
if (DIGIT(number, first) != DIGIT(number, last))
return 0;
}
return 1;
}
int main(int argc, char *argv[])
{
// there can be deffinitely more productive ways to produce input for
// iteration which would cut their domain by the power of ten
#define NUM 1E+3
size_t palindrome = 0, first, last;
for (size_t i = 0; i < NUM; i++) {
for (size_t j = 0; j <= NUM; j++) {
if (is_palindrome(i*j) && (i*j) > palindrome) {
first = i;
last = j;
palindrome = first * last;
}
}
}
printf("%zu * %zu gives the largest palindrome:%zu\n",
first, last, palindrome);
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment