最大的回文产品 - C#
本文关键字:回文 | 更新日期: 2023-09-27 18:32:38
各位程序员大家好
我目前正在尝试用 C# 解决欧拉项目的一些问题,以提高我的知识。但是,我为问题#4制定的一个解决方案即使应该也不起作用。
回文数的两种读法相同。由两个 2 位数字的乘积构成的最大回文是 9009 = 91 × 99。
找到由两个 3 位数字的乘积制成的最大回文。
有什么想法吗?
namespace ProjectEuler_4
{
class Program
{
static void Main(string[] args)
{
for (int i = 999; i >= 100; i--)
{
for (int j = 999; j >= 100; j--)
{
if (isPalindome(i *j) == true)
{
Console.WriteLine("Digit1: " + i);
Console.WriteLine("Digit2: " + j);
Console.WriteLine("Outcome: " + i * j);
Console.ReadLine();
}
else
{
Console.WriteLine(i + " " + j + " =nope");
}
}
}
Console.ReadLine();
}
public static bool isPalindome(int num)
{
string sNum = num.ToString();
for (int i = 0; i < sNum.Length / 2; i++)
if (sNum[i] != sNum[sNum.Length - 1 - i]) return false;
return true;
}
}
}
结果是:
数字1:995数字2:583共:580085
条虽然,这不是正确的答案。我做错了什么?我不是在要求一个完整的解决方案,只是想了解这个解决方案的问题是什么。
尝试检查所有组合。例如,994 * 994更大,您甚至没有检查它。
您的程序实际上可以工作并找到正确的答案。但是,它不会先打印最大的数字,而是第三个输出。
例如,i=999 j=2 在 i=998j=998 之前,但第二个乘积要大得多。看,您不会按降序找到产品。
好的解决方案是一个简单的最大查找循环(有点伪代码):
var best = -1;
for (i, j) {
if (isPalindrome(i*j) && i*j > best) {
best = i*j;
}
}
Console.WriteLine(best);
我有几个注意事项:
- 最好从
i
开始内部循环。 - 如果找到回文,我们可以离开内循环,因为可以保证对于当前
i
没有大于number
的数字
。 - 搜索给出范围中最大乘积的乘法是有意义的
99..9 - 90..0
,因为它们肯定存在于这个范围内。 - 最快的条件应该是
if
语句中的第一个。 - 我对变量使用了
long
类型,以使下面的代码适用于更大的数字。
请尝试以下代码示例:
// Store the maximum palindrome number here:
long maxNumber = 0;
// The maximum multiplicand (typically: 9...9):
const int NMax = 999;
// The minimum multiplicand.
// Obviously, it couldn't be less than 90...0:
const int NMin = NMax - (NMax + 1) / 10 + 1;
for (int i = NMax; i > NMin; i--)
{
// Starting from i since i * j = j * i for any i, j:
for (int j = i; j > NMin; j--)
{
long number = Math.BigMul(i, j);
// The fastest condition should be the first in the `if` statement:
if (number > maxNumber && isPalindome(number))
{
maxNumber = number;
Console.WriteLine("{0} = {1} * {2}", number, i, j);
break; // Leave the `j` loop, because it's guaranteed that there is
// no numbers greater than `number` for the current `i`
}
}
}
输出:
for NMax=999: 906609 = 993 * 913
for NMax=9999: 99000099 = 9999 * 9901
for NMax=9999999: 99956644665999 = 9998017 * 9997647