Answer to Question #266976 in Programming & Computer Science for Likitha.B

Question #266976

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))


1
Expert's answer
2021-11-18T15:15:27-0500


#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;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS