Output of all prime numbers within 100

Output of all prime numbers within 100

Title description:
The output of all prime numbers within 100.
Prime number: A prime number, a natural number that can only be divisible by 1 and itself. The smallest prime number is: 2

Problem-solving ideas:
1. Traverse 2-100;
2. From 2 to the end of the number -1, it is not evenly divisible by the number itself. —> is a prime number
3. In fact, you can calculate 2 to Math.sqrt(i)
4. The key is to make a markboolean isFlag = true;

Summary:
Remember the use of identifiers!

The Java code for this question:

public class PrimeNumberTest {
    
    
	public static void main(String[] args) {
    
    
		
		boolean isFlag = true; //标识i是否被j除尽,一旦能除尽,修改其值
		int count = 0; //记录质数的个数
		
		for(int i=2;i<=100;i++){
    
     //遍历100以内的自然数
			
			for(int j=2;j<=Math.sqrt(i);j++){
    
     //j:被i去除
				
				if(i%j==0){
    
     //i被j除尽
					isFlag = false;
				}
			}
			//判断是否为质数 (即isFlag=true时,是质数)
			if(isFlag == true){
    
    
				System.out.print(i + " ");
				count++;
			}
			//重置isFlag
			isFlag = true;			
		}
		System.out.println();
		System.out.println("质数的总个数为:" + count);
	}
}

Guess you like

Origin blog.csdn.net/qq_45555403/article/details/114155796