Java程序打印100以下的素数
任何大于1的整数,只有两个因数(即1和它本身),称为素数。除了这两个数之外,它没有其他的正除数。在这篇文章中,我们将解释Java程序如何打印1到100之间的素数。
一些素数的例子:2、3、5、7、11等等。
打印100以下素数的步骤
按照以下步骤在Java中打印100以下的素数:
- 声明一个整型变量,例如“A”
- 将变量A除以(A-1到2)
- 如果A不能被任何值(A-1到2)整除,则它是一个素数。
- 对从2到所需限制的所有数字重复此操作。
示例1
以下Java程序打印100以下的素数。
public class First100Primes { public static void main(String args[]){ for(int i = 2; i<=100;){ int prime = 1; for(int loop = 2; loop <=i; loop++) { if((i % loop) == 0 && loop!=i) { prime = 0; } } if (prime != 0){ System.out.println(i +" is a prime number"); i++; } else i++; } } }
输出
2 is a prime number 3 is a prime number 5 is a prime number 7 is a prime number 11 is a prime number 13 is a prime number 17 is a prime number 19 is a prime number 23 is a prime number 29 is a prime number 31 is a prime number 37 is a prime number 41 is a prime number 43 is a prime number 47 is a prime number 53 is a prime number 59 is a prime number 61 is a prime number 67 is a prime number 71 is a prime number 73 is a prime number 79 is a prime number 83 is a prime number 89 is a prime number 97 is a prime number
示例2
这是另一个打印100以下素数的Java程序。
public class First100Primes { public static void main(String[] args) { boolean[] prime = new boolean[100]; for (int i = 2; i < 100; i++) { prime[i] = true; } // finding non-prime numbers for (int i = 2; i * i < 100; i++) { if (prime[i]) { for (int j = i * i; j < 100; j += i) { prime[j] = false; } } } System.out.println("Prime numbers below 100: "); // printing prime numbers for (int i = 2; i < 100; i++) { if (prime[i]) { System.out.print(i + " "); } } } }
输出
Prime numbers below 100: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
广告