Project Euler #36: Double-base palindromes

  • + 0 comments

    100% working C programming

    include

    include

    include

    include

    include

    include

    include

    include

    void to_base(int n, int k, char *result) {

    int index = 0;
    
    while (n > 0) {
        int remainder = n % k;
        result[index++] = (remainder < 10) ? (remainder + '0') : (remainder - 10 + 'a');
        n /= k;
    }
    result[index] = '\0';
    
    int len = strlen(result);
    for (int i = 0; i < len/2; ++i) {
        char temp = result[i];
        result[i] = result[len - 1 - i];
        result[len - 1 - i] = temp;
    }
    

    }

    int is_palindroms(const char *str) {

    int len = strlen(str);
    for (int i = 0; i < len/2; ++i) {
    
        if (str[i] != str[len - 1 - i]) {
            return 0;
        }
    }
    return 1;
    

    }

    int main() {

    int n, k;
    scanf("%d %d", &n, &k);
    
    int sum = 0;
    char base_k[64];
    
    for (int i = 1; i <= n; ++i) {
        char decimal_str[64];
        sprintf(decimal_str, "%d", i);
    
        if (is_palindroms(decimal_str)) {
            to_base(i, k, base_k);
    
            if (is_palindroms(base_k)) {
                sum += i;
            }
        }
    }
    printf("%d\n", sum);
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */    
    return 0;
    

    }