program to print series of prime numbers using java

后端 未结 6 1668
太阳男子
太阳男子 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:07

    Here is your working code:

    import java.io.*;
        class A
        {
            public static void main(String s[]) throws IOException
            {
                int count=2;
                String st;
                System.out.println("how many prime no. do you want");
                BufferedReader obj= new BufferedReader (new InputStreamReader (System.in));
                st=obj.readLine();
                boolean isPrime = false;
    
                int n= Integer.parseInt(st);
                int num=3;
                if(n>=1){
                    System.out.println(2);
                }
                while(count<=n)
                {
                    //No need to go up to num. Up to sqrt(num) will do.
                    for(int i=2;i<=Math.sqrt(num);i++)
                    {
                        if(num%i==0)
                        {
                            isPrime = false;
                            break;
                        }
                    }
                    if(isPrime){
                        System.out.println(num);// Added the print
                        count++;
                    }
                    isPrime = true;
                    num++;
                }
            }
        }
    

提交回复
热议问题