prime distance problem

Problem Description:

Description Now you are given some numbers, and you are asked to write a program that prints the nearest primes to these integers, and prints the distance between them. If there are equidistant prime numbers on the left and right, output the value on the left and the corresponding distance.
If the input integer itself is a prime number, the prime number itself is output, and the distance output is 0
enter
The first line gives the number of test data sets N (0<N<=10000),
the next N lines each have an integer M (0<M<1000000),
output
Each line outputs two integers A B.
Where A represents the closest prime number to the corresponding test data, and B represents the distance between them.
sample input
3
6
8
10
Sample output
5 1
7 1
11 1

#include<cmath>
#include<iostream>
#include<algorithm>
using namespace std;
int isprime(int a) {
	if(a < 2) return 0;
	for(int i = 2; i <= sqrt(a); i++)
		if(a%i==0)
			return 0;
	return 1;
}
int main() {
	int n, x, i, left, right, lenl, leng;
	cin>>n;
	while(n--) {
		cin>>x;
		leng = lenl = 0;
		if(x == 1) {
			lenl = 2;	
		} else {
			for(i = x; ; i--) {
				if(isprime(i)) {
					left = i;
					lenl = x - i;
					break;
				}
			}		
		}
		for(i = x; ; i++) {
			if(isprime(i)) {
				right = i;
				leng = i - x;
				break;
			}
		}
		if(leng < lenl) {
			cout<<right<<" "<<leng<<endl;
		} else {
			cout<<left<<" "<<lenl<<endl;
		}
	}
	return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326040032&siteId=291194637