用Java显示素数

时间:2020-01-09 10:35:26  来源:igfitidea点击:

这篇文章展示了如何在给定范围内以Java生成和显示质数。

如果数字可以除以1或者除以数字本身,则它是质数。因此,给定范围内的每个数字都必须在循环中从2到number / 2进行除法。我们只需要从2到N / 2(其中N是传递的数字)运行循环,原因是没有数字可以被其一半以上的数字完全整除。

Java代码显示给定范围内的质数

import java.util.Scanner;

public class DisplayPrime {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.println("Enter start number for displaying prime numbers  - ");
		int start = sc.nextInt();
		// Since 1 and 0 are not considered prime
		if(start == 0 || start == 1){
			start = 2;
		}
		System.out.println("Enter end number for displaying prime numbers  - ");
		int end = sc.nextInt();
		for(int i = start; i <= end; i++){
			if(isPrimeNumebr(i)){
				System.out.print(i + " ");
			}
		}
	}
	
	private static boolean isPrimeNumebr(int num){
		boolean flag = true;
		for(int i = 2; i < num/2; i++){
			// No remainder means completely divides  
			if(num % i == 0){
				flag = false;
				break;
			}
		}
		return flag;
	}
}

输出:

Enter start number for displaying prime numbers  - 
1
Enter end number for displaying prime numbers  - 
20
2 3 4 5 7 11 13 17 19 

Enter start number for displaying prime numbers  - 
20
Enter end number for displaying prime numbers  - 
100
23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97