//判断用户输入的是否为质数
const readline = require("readline-sync"); console.log("请输入一个数:"); let num = readline.question() - 0; while (isNaN(num) || num <= 0) { console.log("输入有误,请重新输入"); num = readline.question() - 0; } while(num == 1){ console.log("1既不是质数也不是合数"); num = readline.question() - 0; }
//方法一:从2到num-1之间的的数字中,找能被num整除的数字,找得到说明num就不是质数,否则是质数
let a = 0;//临时计数用 for (let i = 2; i < num; i++) { if (num % i == 0) { console.log(num+"不是质数"); a++; break; } } if (a == 0) { console.log(num + "是质数"); }
//方法二:从2到num之间的数字中,找能被num整除的数字,如果这个数字等于num,num就是质数,否则不是质数
for (let i = 2; i <= num; i++) { if(num % i == 0){ if (num == i) { console.log(num + "是质数"); }else{ console.log(num + "不是质数"); break; } } }
//方法三:从1到num之间的数字中,寻找能被num整除的数字,找到计1次次数,最终次数如果为2,num是质数,否则不是质数
let b = 0; for (let i = 1; i <= num; i++) { if (num % i == 0) { b++; } } if(b == 2){ console.log(num + "是质数"); }else{ console.log(num + "不是质数"); }
原文地址:https://www.cnblogs.com/cj-18/p/9063794.html
时间: 2024-11-09 01:53:38