Friday, June 7, 2013

[Project Euler] Problem 4 in C

Problem: Project Euler Problem 4

Probably the fastest I can with isPalindrome()... Brute Force way! I can't think of any way of not doing this brute force. Time to check the Project Euler forum ;)
#include <stdio.h>
#include <stdlib.h>

int main()
{
    int a = 999, b = 999, prod = 0, greatestProd = 0;
    while (a > 0 && b > 0){
        prod = a * b;
        if (prod > greatestProd && isPalindrome(prod))
            greatestProd = prod;

        if (b-- == 1){
            b = 999;
            a--;
        }
    }

    printf("%d\n", greatestProd);
    return 0;
}

int isPalindrome(int num){
    int rev = 0, num_copy = num;
    while (num > 0){
        rev = rev * 10 + num % 10;
        num /= 10;
    }

    return (num_copy == rev) ? 1 : 0;
}

Answer:

No comments:

Post a Comment