我编写了一个程序来打印 1-100 个素数。 请帮我抛出 1-100 范围内的合数异常。 我是初学者,所以任何帮助将不胜感激。
public static void main(String[] args) {
System.out.println("Prime numbers from 1 - 100 are :");
int i = 0;
int x = 0;
for (i = 1; i <= 100; i++) {
int ctr = 0;
for (x = i; x >= 1; x--) {
if (i % x == 0) {
ctr = ctr + 1;
}
}
if (ctr == 2) {
System.out.println(i);
}
}
}
最佳答案
我宁愿实现 isPrime
方法并调用它
public static boolean isPrime(int value) {
if (value <= 1)
return false;
// There's only one even prime: that is two
if ((value % 2) == 0)
return (value == 2);
int from = (int) (Math.sqrt(value) + 1);
// You have to check possible divisors from 3 to sqrt(value)
for (int i = 3; i <= from; i += 2)
if ((value % i) == 0)
return false;
return true;
}
public static void main(String[] args) {
...
for (int i = 1; i <= 100; ++i) {
if (isPrime(i))
System.out.println(i);
else {
// i is not prime. You can do nothing, throw an exception etc
// throw new MyException("Not a prime");
}
}
}
关于java - 程序打印 1-100 素数并对给定范围内的合数抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20840396/