0

Find Distance Java

You are on your way to find the gifts. All the gifts lie in your path in a straight line at prime numbers and your house is at 0. Given your current position find the closest gift to your position, and calculate the distance between your current position and gift and tell the distance. Ex: For input 0, the output is 2 For number = 11, the output should be 0 For number = 2000000000, the output should be 11 For number = 1800000001, the output should be 10

30th Jun 2018, 12:18 PM
Adam Dinesh
Adam Dinesh - avatar
2 Respostas
- 1
C code: Time complexity:O(n) Simple iteration towards both sides of the number and then return the minimum possible nearest prime number of the given element. #include<stdio.h> int check_prime(long int n) { long int i; for(i = 2; i<sqrt(n);i++) { if((n%i)==0) return 0; } return 1; } int main() { long int number,i,j; scanf("%ld",&number); if(check_prime(number)) printf("0\n"); else { for(i=1;i<number-2;i++){ if(check_prime(number-i)){ printf("%d\n",(number-(number-i))); break; } else if(check_prime(number+i)){ printf("%d\n",((number+i)-number)); break; } } } return 0; }
10th Jul 2018, 9:00 AM
Moni
Moni - avatar
- 2
You cannot use Q/A for challenges and if this (and others that you have postes) isnt a challenge, please you have to post your code
30th Jun 2018, 1:03 PM
KrOW
KrOW - avatar