search

Home  >  Q&A  >  body text

java - Problem of finding prime numbers in a range.

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?不赋值为什么没有运行结果?
         }  
        }
    }
某草草某草草2753 days ago848

reply all(1)I'll reply

  • 三叔

    三叔2017-06-07 09:26:09

    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.

    reply
    0
  • Cancelreply