简体   繁体   中英

Prime Number Programme not working

I wanted to create a programme that would display the prime number where the index of the prime number is inputted by the user. Basically the nth prime number would be displayed where n is inputted by the user. The programme however is not working, and any help will be greatly appreciated. The code is written below, could anyone tell me whats wrong with it?

import java.io.*;
public class Nth_Prime
{
    public static void main()throws Exception
    {
        BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Which Prime number would you like to find?");
        int n = Integer.parseInt(stdin.readLine());
        int k = 0;
        int counter = 1;
        int num=0;

    for(int i=3;i<100;i++)
    {
        k=0;
        for(int j=2;j<i;j++)
        {
            if(i%j!=0)
            {
                k++;
            }
        }    
        if(k!=0)
        {
            num=i;
            counter++;
        }
        if(counter==n)


           {
                System.out.println("The number is: "+num);
                break;
            }
        }

    }
}

I got my mistake

    import java.io.*;
public class Nth_Prime
{
    public static void main()throws Exception
    {
        BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Which Prime number would you like to find?");
        int n = Integer.parseInt(stdin.readLine());
        int k = 0;
        int checker = 0;
        int counter = 1;
        int num=0;

        for(int i=3;;i++)
        {
            k=0;
            checker=0;
            for(int j=2;j<i;j++)
            {
                if(i%j==0)
                {
                    checker++;
                }
            }    

            if(checker==0)
            {
                k++;
            }
            if(k!=0)
            {
                num=i;
                counter++;
            }
            if(counter==n)
            {
                System.out.println("The number is: "+num);
                break;
            }
            else
            {
                continue;
            }
        }

    }
}

This is working, but thanks for your help guys

I prefer to create HashMap containing index of prime value and prime value, try this small application:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;

public class Nth_Prime {

    static boolean checkPrime(int n)
    {
        for (int i=2;i<n;i++)
        {
            if(n%i==0)
                return false;
        }
        return true;
    }
    static HashMap<Integer,Integer> map=new HashMap<Integer, Integer>();
    public static void main(String[] args) throws Exception {
        BufferedReader stdin = new BufferedReader(new InputStreamReader(
                System.in));
        map.put(1, 2);
        System.out.println("Which Prime number would you like to find?");
        while(true)
        {
            int n = Integer.parseInt(stdin.readLine());
            if( n<0)
                return;
            if(map.containsKey(n))
            {
                System.out.println("The number is: " + map.get(n));

            }
            else
            {
                int size=map.size();
                int lastKey=size;//(int) map.keySet().toArray()[size-1];
                int lastValue=map.get(lastKey);
                for (int i = lastValue; i < 1000; i++) {

                    if(checkPrime(i))
                    {
                        map.put(size, i);
                        size++;
                        if(map.containsKey(n))
                        {
                            System.out.println("The number is: " + map.get(n));
                            System.out.println("Which Prime number would you like to find?");
                            break;
                        }
                    }
                }
            }


        }


    }
}

Why your code is wrong (gives the wrong output) :: When i is 25 , your inner for loop would increment k when j = 2, 3, 7 ... and after you exit the inner for loop, your if condition if(k!=0) checks, so for 25 your k shall be somewhere around 22 , so you count even 25 as a prime(which is wrong).

Try doing this. I replaced your variable k with a boolean flag , which I set to false every time a i%j == 0 , ie, j divides i (indicating the i is not prime, and hence shall not be counted).

for(int i=3;i<100;i++)
{
    boolean flag = true;
    for(int j=2;j<i;j++)
    {
        if(i%j==0)
        {
            flag = false;
            break;
        }
    }    
    if(flag)
    {
        num=i;
        counter++;
    }
    if(counter==n)
    {
            System.out.println("The number is: "+num);
            break;
    }
}

Few optimizations ::

1) You might consider changing your second for loop to for(int j=2;j<Math.sqrt(i);j++) , since for checking the prime condition, you need not check beyond sqrt(i) , because factors repeat after that.

2) You shall consider using Sieve of Eratosthenes as a more optimal way to finding primes.

try this way:

int num, count, i;
        num=1;
        count=0;
        while (count < nth){

            num=num+1; //find the next prime number 
            for (i = 2; i <= num; i++){

                if (num % i == 0) {

                    break; //prime not found
                }
            }
            if ( i == num){

                count = count+1; //prime found
            }
        }
System.out.println("The number is: "+num);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM