سؤال

I've written some code in C to try adn find whether or not a number is a Palindrome. The rule is that two 3 digit numbers have to be multiplied together and you have to find the highest palindrome. the answer should be 906609 but my code only gets to 580085.

the code:

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

/* Intialise */
void CalcPalin();
int CheckPalin(int number);

/* Functions */
void CalcPalin()
{
    int result = 0;
    int palin = 0;
    int FNumber = 0;
    int FNumber2 = 0;

    int number = 99;
    int number2 = 100;

    while(number2 < 1000)
    {
        number += 1;

        /*times together - calc result*/
        result = number * number2;

        if(CheckPalin(result) == 1)
        {
            palin = result;
            FNumber = number;
            FNumber2 = number2;
        }

        if(number == 999)
        {
            number = 99;
            number2 += 1;
        }
    }
    printf(" Result = %d, by Multiplying [%d] and [%d]", palin, FNumber, FNumber2 );
}

int CheckPalin(int number)
{
    int checknum, checknum2 = 0;

    checknum = number;
    while(checknum)
    {
        checknum2 = checknum2 * 10 + checknum % 10;
        checknum /= 10;
    }

    if( number == checknum2)
        return 1;
    else
        return 0;
}

int main( void)
{
    CalcPalin();
    return EXIT_SUCCESS;
}

Im pretty sure its a stupid answer and im over looking something simple but i cant seem to find it. Any help would be great

هل كانت مفيدة؟

المحلول

You have not tested whether the current result is higher than one old result. Add this check.

// test new result is higher than old palin before setting this as palin
if(CheckPalin(result) == 1 && palin < result) 

نصائح أخرى

Your algorithm print :

 Result = 580085, by Multiplying [583] and [995]

It seems that you should find a way to increment more the 1st number. There is many possibility between 583 and 999 in order to get to 906609.

EDIT : In fact, you are looking for 993 * 913 = 906609.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top