#include <stdio.h>
#include <string.h> // strcmp
// Function to check if a number is a palindrome in a given base
int isPalindrome(unsigned int num, unsigned int base) {
if (base < 2) return 0; // Invalid base
char strnumreversed[65]; // Enough for binary representation of 64-bit number
int len = 0;
unsigned int temp = num;
// Convert number to string in given base
do {
unsigned int digit = temp % base;
strnumreversed[len++] = (digit < 10) ? ('0' + digit) : ('A' + (digit - 10));
temp /= base;
} while (temp > 0);
strnumreversed[len] = '\0';
// Check palindrome
char strnum[65];
for (int i = 0; i < len; ++i) {
strnum[i] = strnumreversed[len - 1 - i];
}
strnum[len] = '\0';
return strcmp(strnumreversed, strnum) == 0;
}
int main() {
unsigned int limit = 1000;
printf("Numbers that are palindromes in both base 10 and base 2:\n");
for (unsigned int i = 1; i <= limit; i++) {
if (isPalindrome(i, 10) && isPalindrome(i, 2)) {
printf("%u (binary: ", i);
// Print binary representation
char binary[65];
int len = 0;
unsigned int temp = i;
do {
binary[len++] = (temp % 2) ? '1' : '0';
temp /= 2;
} while (temp > 0);
// Reverse binary string
for (int j = len - 1; j >= 0; --j) {
putchar(binary[j]);
}
printf(")\n");
}
}
return 0;
}
/*
run:
Numbers that are palindromes in both base 10 and base 2:
1 (binary: 1)
3 (binary: 11)
5 (binary: 101)
7 (binary: 111)
9 (binary: 1001)
33 (binary: 100001)
99 (binary: 1100011)
313 (binary: 100111001)
585 (binary: 1001001001)
717 (binary: 1011001101)
*/