Find third number such that sum of all three number becomes prime
Last Updated :
10 Dec, 2021
Given two numbers A and B. The task is to find the smallest positive integer greater than or equal to 1 such that the sum of all three numbers become a prime number.
Examples:
Input: A = 2, B = 3
Output: 2
Explanation:
The third number is 2 because if we add all three number the
sum obtained is 7 which is a prime number.
Input: A = 5, B = 3
Output: 3
Approach:
- First of all store the sum of given 2 number in sum variable.
- Now, check if bitwise and (&) of sum and 1 is equal to 1 or not (checking if the number is odd or not).
- If it is equal to 1 then assign 2 to variable temp and go to step 4.
- Else check sum value of sum and temp variable whether it is prime number or not. If prime, then print the value of temp variable else add 2 to temp variable until it is less than a prime value.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
bool prime( int n)
{
for ( int i = 2; i * i <= n; i++) {
if (n % i == 0)
return false ;
}
return true ;
}
void thirdNumber( int a, int b)
{
int sum = 0, temp = 0;
sum = a + b;
temp = 1;
if (sum & 1) {
temp = 2;
}
while (!prime(sum + temp)) {
temp += 2;
}
cout << temp;
}
int main()
{
int a = 3, b = 5;
thirdNumber(a, b);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static boolean prime( int n)
{
for ( int i = 2 ; i * i <= n; i++)
{
if (n % i == 0 )
return false ;
}
return true ;
}
static void thirdNumber( int a, int b)
{
int sum = 0 , temp = 0 ;
sum = a + b;
temp = 1 ;
if (sum == 0 )
{
temp = 2 ;
}
while (!prime(sum + temp))
{
temp += 2 ;
}
System.out.print(temp);
}
static public void main (String []arr)
{
int a = 3 , b = 5 ;
thirdNumber(a, b);
}
}
|
Python3
def prime(n):
for i in range ( 2 , n + 1 ):
if i * i > n + 1 :
break
if (n % i = = 0 ):
return False
return True
def thirdNumber(a, b):
summ = 0
temp = 0
summ = a + b
temp = 1
if (summ & 1 ):
temp = 2
while (prime(summ + temp) = = False ):
temp + = 2
print (temp)
a = 3
b = 5
thirdNumber(a, b)
|
C#
using System;
class GFG
{
static bool prime( int n)
{
for ( int i = 2; i * i <= n; i++)
{
if (n % i == 0)
return false ;
}
return true ;
}
static void thirdNumber( int a, int b)
{
int sum = 0, temp = 0;
sum = a + b;
temp = 1;
if (sum == 0)
{
temp = 2;
}
while (!prime(sum + temp))
{
temp += 2;
}
Console.Write (temp);
}
static public void Main ()
{
int a = 3, b = 5;
thirdNumber(a, b);
}
}
|
Javascript
<script>
function prime(n)
{
for (let i = 2; i * i <= n; i++) {
if (n % i == 0)
return false ;
}
return true ;
}
function thirdNumber(a, b)
{
let sum = 0, temp = 0;
sum = a + b;
temp = 1;
if ((sum & 1) != 0) {
temp = 2;
}
while (!prime(sum + temp)) {
temp += 2;
}
document.write(temp);
}
let a = 3, b = 5;
thirdNumber(a, b);
</script>
|
Time Complexity: O(sqrt(n))
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...