找到由两个3位数字的乘积制成的最大回文 [英] Find the largest palindrome made from the product of two 3-digits num
问题描述
我正在解决第四个项目Euler问题,找到由两个3位数字的乘积制成的最大回文,代码:
#include < iostream >
使用 命名空间标准;
int reverse( int num)
{
int num2 = 0 ;
while (num> 0 )
{
num2 * = 10 ;
num2 + =(num% 10 );
num =(num - (num% 10 ))/ 10 ;
}
return num2;
}
bool is_planidormic( int num)
{
int rev = reverse(num);
if (rev == num)
{
return < span class =code-keyword> true ;
}
返回 false ;
}
int main()
{
int num = 0 ,largest_plan = 0 ;
for ( int i = 100 ; i< 1000 ; i ++)
{
for (< span class =code-keyword> int j = 100 ; j< 1000 ; j ++)
{
num = i * j;
if (is_planidormic(num))
{
largest_plan = num;
}
}
}
cout<< largest_plan<< ENDL;
}
此代码达到580085但是我用Google搜索并发现它是更大的解决方案。
错误在哪里?
谢谢,Samuel。
首先调试你的软件!
检查双循环中的迭代:
for ( int i = 100 ; i< 1000 ; i ++)
{
for ( int j = 100 ; j< 1000 ; j ++)
{
num = i * j;
if (is_planidormic(num))
{
largest_plan = num;
}
}
}
您会看到产品'num'每次从低值重新启动新的内循环重启。因此,在最后一次迭代中你会得到一个小于'官方'解决方案906609的新回文,因为你将回文放在'largest_plan'中而不进行检查。
将你的代码更改为:
for ( int i = 100 ; i< 1000 ; i ++)
{
for ( int j = 100 ; j< 1000 ; j ++)
{
num = i * j;
if (is_planidormic(num))
{
if ( num> largest_plan) // 检查实际数字是否大于前者
{
largest_plan = num;
}
}
}
}
你会得到正确的答案。 />
PS:我赞赏downvote,但留下关于它的说明会好得多,所以我和其他人可以理解哪里出错了。 ..
Hi, I was solving the 4th Project Euler problem to find the largest palindrome made from the product of two 3-digit numbers, The code :
#include <iostream>
using namespace std;
int reverse(int num)
{
int num2 = 0;
while (num > 0)
{
num2 *= 10;
num2 += (num % 10);
num = ( num - ( num % 10 ) ) / 10;
}
return num2;
}
bool is_planidormic(int num)
{
int rev = reverse(num);
if (rev == num)
{
return true;
}
return false;
}
int main()
{
int num = 0,largest_plan = 0;
for (int i = 100; i < 1000; i++)
{
for (int j = 100; j < 1000; j++)
{
num = i*j;
if (is_planidormic(num))
{
largest_plan = num;
}
}
}
cout << largest_plan << endl;
}
This code reaches 580085 but I googled and found that are larger solution.
Where is the error ?
Thanks, Samuel.
First of all debug your software!
Checking through iterations in the double loop:
for (int i=100; i < 1000; i++) { for (int j=100; j < 1000; j++) { num = i*j; if (is_planidormic(num)) { largest_plan = num; } } }
You will see that the product 'num' restarts from low values each time a new inner loop restarts. So happen that on the last iteration you get a new palindrome that is smaller than the 'official' solution, 906609, because you put the palindrome in 'largest_plan' without checking.
Change your code to:
for (int i=100; i < 1000; i++) { for (int j=100; j < 1000; j++) { num = i*j; if (is_planidormic(num)) { if (num > largest_plan) //Check if actual number is larger that the former { largest_plan = num; } } } }
And you'll get the correct answer.
P.S.: I appreciated the downvote, but it would be much better to leave a note about it, so I, and others, could understand where is the wrong...
这篇关于找到由两个3位数字的乘积制成的最大回文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!