一个数要成为另一个数的因子,它必须能被该数整除(余数为 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)
- 如果满足上述条件,则显示该数字。
另请阅读