要成为一个数的因数,因数应该整除这个数(余数为0)。例如,
12的因数是1、2、3、4 、6 和 12。
示例: 正数的因数
// program to find the factors of an integer // take input const num = prompt('Enter a positive number: '); console.log(`The factors of ${num} is:`); // looping through 1 to num for(let i = 1; i <= num; i++) { // check if number is a factor if(num % i == 0) { console.log(i); } }
输出
Enter a positive number: 12 The factors of 12 is: 1 2 3 4 6 12
在上面的程序中,提示用户输入一个正整数。
for
循环用于通过 1 循环到用户输入的数字。
模数运算符 %
用于检查 num 是否可整除。
在每次迭代中,检查条件是否num 可以被i 整除。
if(num % i == 0)