检查质数的Java程序
什么是质数?
素数是只能被 1 或自身整除的数。例如,11 只能被 1 或自身整除。其他素数 2、3、5、7、11、13、17……
注意: 0 和 1 不是素数。 2是唯一的偶素数。
检查数字是否为素数的 Java 程序
程序逻辑:
- 我们需要将一个输入数字(例如 17)从 2 到 17 相除,然后检查余数。如果余数为 0,则数不是素数。
- 没有一个数能被自身的一半以上整除。所以我们只需要遍历
numberToCheck/2
.如果输入是 17,一半是 8.5,循环将遍历值 2 到 8 - 如果一个 numberToCheck 完全可以被其他数字整除,则标志 isPrime 设置为
false
并退出循环。
public class PrimenumberToCheckCheck { public static void main(String[] args) { int remainder; boolean isPrime=true; int numberToCheck=17; // Enter the numberToCheckber you want to check for prime //Loop to check whether the numberToCheckber is divisible any numberToCheckber other than 1 and itself for(int i=2;i<=numberToCheck/2;i++) { //numberToCheckber is divided by itself remainder=numberToCheck%i; System.out.println(numberToCheck+" Divided by "+ i + " gives a remainder "+remainder); //if remainder is 0 than numberToCheckber is not prime and break loop. Else continue the loop if(remainder==0) { isPrime=false; break; } } // Check value true or false, if isprime is true then numberToCheckber is prime otherwise not prime if(isPrime) System.out.println(numberToCheck + " is a Prime numberToCheckber"); else System.out.println(numberToCheck + " is not a Prime numberToCheckber"); } }
输出:
17 Divided by 2 gives a remainder 1 17 Divided by 3 gives a remainder 2 17 Divided by 4 gives a remainder 1 17 Divided by 5 gives a remainder 2 17 Divided by 6 gives a remainder 5 17 Divided by 7 gives a remainder 3 17 Divided by 8 gives a remainder 1 17 is a Prime Number
查看我们的程序以查找从 1 到 100 的素数
java