Write a c code to perform binary search. If the element is present print its next
nearest prime number. If the element is not present print -1.
EXAMPLE:
Input:
10 20 30 40 50 60 70 80 90 100
Search element-50
Output: 53 (50 is present so print 53(next nearest prime number))
#include<stdio.h>
#include<cmath>
int isPrime(int num) {
if (num < 2){
return 0;
}
if (num == 2 || num == 3){
return 1;
}
for (int i = 2; i <= sqrt(num*1.0); i++){
if (num % i == 0){
return 0;
}
}
return 1;
}
int main(){
int c, first, last, middle, n=10, search,i;
int numbers[]={10,20,30,40,50,60,70,80,90,100};
printf("Enter search element: ");
scanf("%d",&search);
first = 0;
last = n - 1;
middle = (first+last)/2;
while (first <= last) {
if (numbers[middle] < search){
first = middle + 1;
}else if (numbers[middle] == search) {
for(i=search;i<=10000;i++){
if(isPrime(i)==1){
printf("%d is the next nearest prime number.\n", i);
break;
}
}
break;
}
else{
last = middle - 1;
}
middle = (first + last)/2;
}
if (first > last){
printf("Not found! %d isn't present in the list.\n", search);
}
getchar();
getchar();
return 0;
}
Comments
Leave a comment