Wednesday, November 22, 2017

Square of Prime Closest to Sum

Two numbers N1, N2 are passed as input. The program must find the closest prime number to their sum and then print the square of that prime number. If there are multiple prime numbers which are the closest to the sum, then the program must print -1.

Input Format:
The first line will contain the number N1 The second line will contain the number N2

Boundary Conditions: 1 <= N1 <= 99999999 1 <= N2 <= 99999999

Output Format: The square of the prime number as per the conditions mentioned above.

Example Input/Output 1:
Input:
2
1
Output:
9
Explanation: The sum of the numbers is 3. The prime number closest to 3 is 3 itself. Hence square of 3 = 9 is printed as output.

Solution 1:
def prime(x):
    for i in range(2,int(x**(0.5))):
        if x%i==0:
            return 0
    return 1
s,i,j=int(input())+int(input()),0,0
while 1:
    if prime(s-i) and prime(s+j): break
    elif not prime(s-i): i+=1
    else: j+=1
if i==0: print(s*s)
elif i==j: print('-1')
elif i>j: print((s+j)**2)
else: print((s-i)**2)
Share: