Represent the given number as the sum of two composite numbers
Last Updated :
10 Mar, 2022
Given an integer N, the task is to represent N as the sum of two composite integers. There can be multiple ways possible, print any one of them. If it is not possible to represent the number as the sum of two composite numbers then print -1.
Examples:
Input: N = 13
Output: 4 9
4 + 9 = 13 and both 4 and 9 are composite.
Input: N = 18
Output: 4 14
Approach: When N ? 11 then only 8 and 10 are the integers which can be represented as the sum of two composite integers i.e. 4 + 4 and 4 + 6 respectively.
When N > 11 then there are two cases:
- When N is even: N can be represented as 4 + (N – 4) since both are composite.
- When N is odd: N can be represented as 9 + (N – 9).
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void findNums( int n)
{
if (n <= 11) {
if (n == 8)
cout << "4 4" ;
if (n == 10)
cout << "4 6" ;
else
cout << "-1" ;
return ;
}
if (n % 2 == 0)
cout << "4 " << (n - 4);
else
cout << "9 " << (n - 9);
}
int main()
{
int n = 13;
findNums(n);
return 0;
}
|
Java
class GFG
{
static void findNums( int n)
{
if (n <= 11 )
{
if (n == 8 )
System.out.print( "4 4" );
if (n == 10 )
System.out.print( "4 6" );
else
System.out.print( "-1" );
return ;
}
if (n % 2 == 0 )
System.out.print( "4 " + (n - 4 ));
else
System.out.print( "9 " + (n - 9 ));
}
public static void main(String args[])
{
int n = 13 ;
findNums(n);
}
}
|
Python3
def findNums(n):
if (n < = 11 ):
if (n = = 8 ):
print ( "4 4" , end = " " )
if (n = = 10 ):
print ( "4 6" , end = " " )
else :
print ( "-1" , end = " " )
if (n % 2 = = 0 ):
print ( "4 " , (n - 4 ), end = " " )
else :
print ( "9 " , n - 9 , end = " " )
n = 13
findNums(n)
|
C#
using System;
class GFG
{
static void findNums( int n)
{
if (n <= 11)
{
if (n == 8)
Console.Write( "4 4" );
if (n == 10)
Console.Write( "4 6" );
else
Console.Write( "-1" );
return ;
}
if (n % 2 == 0)
Console.Write( "4 " + (n - 4));
else
Console.Write( "9 " + (n - 9));
}
public static void Main()
{
int n = 13;
findNums(n);
}
}
|
Javascript
<script>
function findNums(n)
{
if (n <= 11)
{
if (n == 8)
document.write( "4 4" );
if (n == 10)
document.write( "4 6" );
else
document.write( "-1" );
return ;
}
if (n % 2 == 0)
document.write( "4 " + (n - 4));
else
document.write( "9 " + (n - 9));
}
var n = 13;
findNums(n);
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...