Alex Balauca Alex Balauca - 20 days ago 9
C Question

Finding the numbers that are palindromic in both base 2 and 10 and summing them up

I need to find the sum of all numbers that are less or equal with my input number (it requires them to be palindromic in both radix 10 and 2). Here is my code:

#include <stdio.h>
#include <stdlib.h>

int pal10(int n) {
int reverse, x;
x = n;
while (n != 0) {
reverse = reverse * 10 + n % 10;
n = n / 10;
}
if (reverse == x)
return 1;
else
return 0;
}

int length(int n) {
int l = 0;
while (n != 0) {
n = n / 2;
l++;
}
return l;
}

int binarypal(int n) {
int v[length(n)], i = 0, j = length(n);
while (n != 0) {
v[i] = n % 2;
n = n / 2;
i++;
}
for (i = 0; i <= length(n); i++) {
if (v[i] == v[j]) {
j--;
} else {
break;
return 0;
}
}
return 1;
}

int main() {
long s = 0;
int n;

printf("Input your number \n");
scanf("%d", &n);

while (n != 0) {
if (binarypal(n) == 1 && pal10(n) == 1)
s = s + n;
n--;
}
printf("Your sum is %ld", s);
return 0;
}


It always returns 0. My guess is I've done something wrong in the
binarypal
function. What should I do?

Answer

You have multiple problems:

  • function pal10() fails because reverse is not initialized.

  • function binarypal() is too complicated, you should use the same method as pal10().

  • you should avoid comparing boolean function return values with 1, the convention in C is to return 0 for false and non zero for true.

  • you should avoid using l for a variable name as it looks very similar to 1 on most constant width fonts. As a matter of fact, it is the same glyph for the original Courier typewriter font.

Here is a simplified and corrected version with a multi-base function:

#include <stdio.h>
#include <stdlib.h>

int ispal(int n, int base) {
    int reverse = 0, x = n;

    while (n > 0) {
        reverse = reverse * base + n % base;
        n = n / base;
    }
    return reverse == x;
}

int main(void) {
    long s = 0;
    int n = 0;

    printf("Input your number:\n");
    scanf("%d", &n);

    while (n > 0) {
        if (ispal(n, 10) && ispal(n, 2))
            s += n;
        n--;
    }
    printf("Your sum is %ld\n", s);
    return 0;
}
Comments