找到最大的回文数,它是两个简单(素数)五位数的乘积。 Java脚本 [英] Finding he largest palindromic number, which is the product of two simple (prime) five-digit numbers. Javascript
问题描述
我正在尝试编写一个程序,该程序返回最大回文数,该数是两个简单的五位数字的乘积,并返回因子本身。
I was trying to write a program that returns the largest palindromic number, which is the product of two simple five-digit numbers, and returns the factors themselves.
质数是仅被1除以其本身的自然数(2、3、5、7、11 ...)
A prime number is a natural number that is divided only by 1 and itself (2, 3, 5, 7, 11, ...)
回文数读为两种方式都一样(例如ABBA)。
A palindromic number reads the same both ways (for example, ABBA).
if(isPalin(mul) && isPrime(i) && isPrime(j))
function isPrime(i){
for (var k = 2; k <= i; k++) {
if (i%k===0 && i!==k) {
return false;
}
}
return true;
}
<!--code-->
<script>
function largestPalindrome(){
for(var i = 99999; i>10000; i--){
for(var j = 99999; j>10000; j--){
var mul = j*i;
if(isPalin(mul) && isPrime(i) && isPrime(j)){
return i * j;
}
}
}
}
function isPalin(i){
return i.toString() == i.toString().split("").reverse().join("");
}
function isPrime(i){
for (var k = 2; k <= i; k++) {
if (i%k===0 && i!==k) {
return false;
}
}
return true;
}
console.log(largestPalindrome());
</script>
当我运行此程序时,它不会在控制台中显示任何内容并且我不确定为什么。
When I run this program it does not display anything in the console and I am not sure why.
推荐答案
查看此链接,以提高算法的时间复杂度。另外,此,以了解时间复杂性如何影响程序效率。
Look this link for time-complexity of algorithms. Also this to see how time-complexity can influence to your program efficiency.
这部分不是很精确,但可以提供帮助。您的第一个循环运行时间为 99999-10000
。这也适用于第二循环。在最坏的情况下, isPrime
运行(99999)
。因此 if(i%k === 0&& i!== k)返回false;
运行 total_ops =(99999-10000) ^ 2 *(99999)
次(我们跳过了代码的其他部分)。如果您的程序是用c ++编写的,比Java脚本更快,那么它可以每秒运行 2 *(10 ^ 8)
simple 操作。您的程序运行时间约为(显然大于) total_ops /(2 * 10 ^ 8)
(我建议对它进行估算以得到一个估计值...)。
This part is not very precise but it can help. Your first loop runs 99999-10000
time. Also this holds for second loop. The isPrime
in the worst case runs (99999)
. So if (i%k===0 && i!==k) return false;
runs total_ops = (99999-10000)^2*(99999)
times(we skip other part of your code). If your program written in c++ which is more faster than java-script it can run about 2*(10^8)
simple operation per second. Your program run time is about(obviously more than) total_ops/(2*10^8)
(I suggest calculate it to have an estimation...).
PS:您可以在函数上打印以确保其进度...
PS: You can put print to your functions to ensure about their progress...
这篇关于找到最大的回文数,它是两个简单(素数)五位数的乘积。 Java脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!