这是如何工作的?你能一步一步解释吗?
// function to show primes
function showPrimes(n) {
for (let i = 2; i < n; i++) {
if (!isPrime(i)) continue;
console.log(i); // a prime
}
}
// function to check prime
function isPrime(n) {
for (let i = 2; i < n; i++) {
if (n % i == 0) return false;
}
return true;
}
// trigger to run the function and put the value of (n)
showPrimes(10);
答案 0 :(得分:0)
// function declaration
function showPrimes(n) {
//For loop from first prime number to number of prime numbers to be printed (10)
for (let i = 2; i < n; i++) {
// Condition to check if a number is prime or not
if (!isPrime(i))
continue; //if it is not prime, then loop will continue to next iteration
console.log(i); // a prime will be shown
}
}
// Function declaration
function isPrime(n) {
//For loop to iterate till the given number that is to be checked for being prime or not
for (let i = 2; i < n; i++) {
// If in any case the number is divisible by any number between 2 to n, then its not prime
if (n % i == 0)
return false;
}
return true; // no need for an else after a return
}
showPrimes(10); // execute
答案 1 :(得分:0)
isPrime
是一个接受数字并返回true
的函数,如果数字是素数则返回false
。
isPrime()
的工作方式:
素数是可以除
0
以外的任何数字并可以自我编号的数字
或者换句话说,可以被1
与其本身不是质数的数字整除的数字。
for (let i = 2; i < n; i++) //creates a loop with 2 to n-1.
if ( n % i == 0) return false; //checks if that number is divisible by 'i'. If it is it return false
如果循环内未返回false
,则意味着n
不能被2
到n-1
的任何数字整除。因此,在循环true
返回之后
showPrimes
的工作方式:
showPrimes()
的参数为n
,这是显示质数的限制。
for (let i = 2; i < n; i++) //creates a loop from 2 to n-1
下一行检查该数字是否不是素数。如果不是素数,则continue;
if (!isPrime(i)) continue;
continue语句终止当前循环或标记循环的当前迭代中的语句执行,并在下一次迭代中继续执行循环
或者简单地,如果数字isPrime(i)
返回false
,循环将不会到达该行
console.log(i);
然后转到下一个号码。