Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

Java Exercises: Get the position of a given prime number

Java Basic: Exercise-198 with Solution

Write a Java program to get the position of a given prime number.

Pictorial Presentation:

Java Basic Exercises: Get the position of a given prime number

Sample Solution:

Java Code:

import java.util.*;
public class Solution {
 public static void main(String[] args) {
  Scanner in = new Scanner(System.in);
  System.out.print("Input a prime number: ");
  int n = in .nextInt();
  System.out.print("Position of the said Prime number: " + kth_Prime(n));
 }
 public static int kth_Prime(int n) {
  int[] prime_num = new int[10000];
  int num = 3;
  int i = 0, index = 0;
  prime_num[0] = 2;
  while (num <= n) {
   for (i = 0; i <= index; i++) {
    if (num % prime_num[i] == 0) {
     break;
    }
   }
   if (i > index) {
    prime_num[++index] = num;
   }
   num++;
  }
  return index + 1;
 }
}

Sample Output:

Input a prime number:  13
Position of the said Prime number: 6

Flowchart:

Flowchart: Java exercises: Get the position of a given prime number

Java Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Java program to test if a given number (positive integer ) is a perfect square or not.
Next: Write a Java program to check a string follows a given pattern.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Java: Tips of the Day

How to sort an ArrayList?

Collections.sort(testList);
Collections.reverse(testList);

That will do what you want. Remember to import Collections though!

Ref: https://bit.ly/32urdSe