回文中两个3位数的乘积

时间:2018-09-23 02:09:58

标签: c palindrome

我编写了以下代码,以查找由两个3位数字的乘积获得的第一个回文:

#include <stdio.h>

int main()
{
 int pro,d,sum=0,c;
 for (int a=100;a<1000;a++)
{
    for (int b=a;b<1000;b++)
    {
        pro=a*b;
        d=pro;
        while (d!=0)
        {
            c=d%10;
            sum= sum*10 + c;
            d=d/10;
        }
        if (sum==pro)
        {
            printf("%d is a palindrome \n",sum);
            return 0;
        }
    }
}
 return 0;
}

但是当我运行代码时,它没有任何输出。 有帮助吗?

1 个答案:

答案 0 :(得分:0)

您需要在每次迭代或内部for循环之后重置总和值,否则它将在下一个后续迭代中使用上一个迭代值。

代码:

#include <stdio.h>

int main()
{
   int pro,d,sum=0,c;
 for (int a=100;a<1000;a++)
{
    for (int b=a;b<1000;b++)
    {
        pro=a*b;
        d=pro;
        while (d!=0)
        {
            c=d%10;
            sum= sum*10 + c;
            d=d/10;
        }
        if (sum==pro)
        {
            printf("%d is a palindrome \n",sum);
            return 0;
        }
        sum=0;
    }
}

    return 0;
}

输出:

10201 is a palindrome
相关问题