Search code examples
javaalgorithmloopsnested-loopsprimes

generating a nth prime number without using 'isprime()' function


there is no output for the code when the input exceeds two.

import java.util.Scanner;


class PrimeNumberFinder {
    static boolean is_prime(int number ,int[] prime_numbers) {
        boolean is_prime = true;
        for (int primeNumber : prime_numbers) {
            if( primeNumber != 0) {
                if ((number % primeNumber) == 0) {
                    is_prime = false;
                    break;
                }else {continue;}
            }else {continue ;}
        }
        return is_prime;
    }
}

public class Main {
    public static void main(String []args){
        Scanner n = new Scanner(System.in) ;
        System.out.println("Enter the nth prime number you want: ");

        int num = n.nextInt();

        int[] primes = new int[num];
        int prime = 2;
        primes[0] = 2;
        if (num > 1) {
        do {
            int num_primes = 0;
            num_primes ++;
            prime ++;
            if (PrimeNumberFinder.is_prime(prime, primes)) {primes[num_primes] = prime;}
            continue;
        } while (primes[num - 1] == 0);}
        System.out.printf("Your Prime number is %d",primes[num -1]);
    }
}

I was trying to create a cli application that generates a nth prime number with input n. the above code is not generating any output after 2 i guess any one of the loop is not functioning properly.


Solution

  • There are two issues:

    • num_primes is redefined with value 0 at every iteration of the do loop and so primes[num_primes] = prime; is always doing primes[1] = prime;. num_primes should only be initialised once -- outside the loop.
    • num_primes++ is executed in every iteration of the loop, but this should only happen if a prime was found.
    • Not a problem, but continue as the last statement in a loop body is useless.

    Corrected code:

            if (num > 1) {
                int num_primes = 0; // Initialise before loop
                do {
                    prime ++;
                    if (PrimeNumberFinder.is_prime(prime, primes)) {
                        // Only increment when prime
                        primes[++num_primes] = prime;
                    }
                } while (primes[num - 1] == 0);
            }