i th prime number java code example

Example 1: nth prime number java

import java.util.Scanner;
public class NthPrime {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.print("Enter n to compute the nth prime number: ");
    int nth = sc.nextInt(); 
    int num, count, i;
    num=1;
    count=0;
 
    while (count < nth){
      num=num+1;
      for (i = 2; i <= num; i++){ //Here we will loop from 2 to num
        if (num % i == 0) {
          break;
        }
      }
      if ( i == num){//if it is a prime number
        count = count+1;
      }
    }
    System.out.println("Value of nth prime: " + num);
  }
}

Example 2: checking if a given integer is a prime number java

public class Prime {

    public static void main(String[] args) {

        int num = 29;
        boolean flag = false;
        for(int i = 2; i <= num/2; ++i)
        {
            // condition for nonprime number
            if(num % i == 0)
            {
                flag = true;
                break;
            }
        }

        if (!flag)
            System.out.println(num + " is a prime number.");
        else
            System.out.println(num + " is not a prime number.");
    }
}

Tags:

Java Example