AF
HomeTagSubmit NotesAsk AnythingLoginSubscribe Us
AF
1. Feel Free to ask and submit anything on Anyforum.in 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 133
basics x 162
Posted On : 2017-07-13 19:53:41.0
profile hemana mana - anyforum.in hemana mana
1240
up-rate
6
down-rate

Answers


import java.util.Scanner;

public class PrimeDifferenceCalculator {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
int N=input.nextInt();
int K=0;
int nearestPrime=N;
int output=0;
int temp=N;
while(!isPrime(K) && K!=1){
if(isPrime(nearestPrime)){
K=nearestPrime-temp;
output=(nearestPrime-N==1)?1:nearestPrime;
nearestPrime=K;
temp=K;
}else{
nearestPrime++;
}
}
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
Are You Satisfied : 4 Yes  2 NO
profile Garima Gupta - anyforum.in Garima Gupta
596127620267
Reply This Thread
up-rate
3
down-rate
Comments
can possible any other way using string or array?
profile Divesh - anyforum.in Divesh
19  0  0
Posted On :2017-07-17 11:47:37.0
Leave a Comment
Hi,
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 - anyforum.in Garima Gupta
596  1276  20267
Posted On :2017-07-17 19:56:17.0
Leave a Comment



Post Answer
Please Login First to Post Answer: Login login with facebook - anyforum.in