program to print series of prime numbers using java

后端 未结 6 1606
太阳男子
太阳男子 2021-01-25 01:40

This code is to print the series of prime number up to given limit but when I am trying to execute this,it goes into infinite loop.

import java.io.*;
class a
{
          


        
6条回答
  •  礼貌的吻别
    2021-01-25 02:29

    You can take a look at this code.

    import java.io.*;
    public class Main {
    
         public static void main(String[] args) throws IOException {
    
            BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
            //How many prime numbers you want to print?
            String s = bf.readLine();
            int n = Integer.parseInt(s);
            int count = 0;
            boolean loop = true;
            for(int i =2 ; loop ; i++){
    
                if(isPrime(i))
                    {
                    System.out.println(i + " ");
                    count++;
                    }
                if(count == n)
                    loop = false;
            }
        }
    

    The following isPrime() method checks whether a number is prime or not. If the number is prime, it returns true, otherwise false.

        public static boolean isPrime(int num) {
            boolean prime = true;
            for(int i=2 ; i<= Math.sqrt(num);){
                if(num % i ==  0)
                    {
                        prime = false;
                        break;
                    }
                if(i >= 3)
                /* when i>=3 we do not need to check for every number. 
                  For avoiding even numbers i is incremented by 2. 
                  It reduces the number of looping */ 
                    i+=2;
                else
                    i++;
            }
    
            return prime;
    
        }
    }
    

提交回复
热议问题