HomeTagSubmit NotesAsk AnythingLoginSubscribe Us
1. Feel Free to ask and submit anything on and get satisfactory answer
2. Registration is not compulsory, you can directly login via google or facebook
3. Our Experts are looking for yours ?.

programming-basics: Java program to find the total prime differences

Write a java program to take an integer N.Find the closest prime number to that integer and calculate the difference between N and that closest prime number and let that difference be K.Now find the closest prime number to K and calculate the difference.Continue this process iteratively until that difference value itself is a prime or their difference is 1.The final computed value is the Total Prime Difference of N. Sample Input: 36 Sample Output: Total prime difference of 36 is 1 Sample Input: 583 Sample Output: Total prime difference of 583 is 5 Explanation: Here closest prime number of 36 is 37 and their difference is 37-36=1. Hence as1 itself is prime ,that will be the total prime difference of 36. In the second case closest prime of 583 is 587. Their difference is 4. Now closest prime of 4 is 5.Hence the answer will be 5.

programming x 136
basics x 164
Posted On : 2017-07-13 19:53:41.0
profile hemana mana - hemana mana


import java.util.Scanner;

public class PrimeDifferenceCalculator {
public static void main(String[] args) {
Scanner input=new Scanner(;
int N=input.nextInt();
int K=0;
int nearestPrime=N;
int output=0;
int temp=N;
while(!isPrime(K) && K!=1){
System.out.println("Total prime difference of "+N+" is "+output);
private static boolean isPrime(int num) {
if (num < 2) return false;
if (num == 2) return true;
if (num % 2 == 0) return false;
for (int i = 3; i * i <= num; i += 2)
if (num % i == 0) return false;
return true;

Posted On : 2017-07-13 23:48:36
Satisfied : 4 Yes  2 No
profile Garima Gupta - Garima Gupta
Reply This Thread
can possible any other way using string or array?
profile Divesh - Divesh
33  0  0
Posted On :2017-07-17 11:47:37.0
Leave a Comment
Why do you want to use Array or String if not required? Please let me know where you want to use array, I´ll try to do it and post the code here.
profile Garima Gupta - Garima Gupta
596  1276  21100
Posted On :2017-07-17 19:56:17.0
Leave a Comment

Post Answer
Please Login First to Post Answer: Login login with facebook -