java - Problem of finding prime numbers in a range.
某草草
某草草 2017-06-07 09:24:09
0
1
840

package text;

   import java.util.Scanner;  

public class test {

public static void main(String[] args) {  
         Scanner in = new Scanner(System.in);  
         int x;  
         x = in.nextInt();  
         boolean isprime = true;  
           
         for (int i = 2; i <= x; i++) {  
             for(int j = 2; j < i; j++) {  
                   if(i % j == 0)            {  
                     isprime = false;  
                     break;  
                   }  
             }  
             if(isprime)      System.out.print(i + " ");  
             isprime = true;  //这里为什么一定要重新赋值true?不赋值为什么没有运行结果?
         }  
        }
    }
某草草
某草草

reply all(1)
三叔

The isprime variable can be regarded as a flag. In the program, it is decided whether to print i based on the last value of isprime. As for why the value is reassigned as you asked, this is to prepare for the next round of the loop. If the value of isprime is not initialized to true, then i cannot be printed even if i is a prime number.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template