Skip to content
Related Articles

Related Articles

Find three prime numbers with given sum

View Discussion
Improve Article
Save Article
  • Last Updated : 05 Jan, 2021

Given an integer N, the task is to find three prime numbers X, Y, and Z such that the sum of these three numbers is equal to N i.e. X + Y + Z = N.

Examples:  

Input: N = 20 
Output: 2 5 13

Input: N = 34 
Output: 2 3 29 

Approach:  

  • Generate prime numbers using Sieve of Eratosthenes
  • Start from the first prime number.
  • Take another number from the generated list.
  • Subtract first number and second number from the original number to obtain the third number.
  • Check if the third number is a prime number.
  • If the third number is a prime number then output the three numbers.
  • Otherwise, repeat the process for the second number and consequently the first number
  • If the answer does not exist then print -1.

Below is the implementation of the above approach:  

C++




// C++ implementation of the approach
 
#include <bits/stdc++.h>
using namespace std;
 
const int MAX = 100001;
 
// The vector primes holds
// the prime numbers
vector<int> primes;
 
// Function to generate prime numbers
void initialize()
{
 
    // Initialize the array elements to 0s
    bool numbers[MAX] = {};
    int n = MAX;
    for (int i = 2; i * i <= n; i++)
        if (!numbers[i])
            for (int j = i * i; j <= n; j += i)
 
                // Set the non-primes to true
                numbers[j] = true;
 
    // Fill the vector primes with prime
    // numbers which are marked as false
    // in the numbers array
    for (int i = 2; i <= n; i++)
        if (numbers[i] == false)
            primes.push_back(i);
}
 
// Function to print three prime numbers
// which sum up to the number N
void findNums(int num)
{
 
    bool ans = false;
    int first = -1, second = -1, third = -1;
    for (int i = 0; i < num; i++) {
 
        // Take the first prime number
        first = primes[i];
        for (int j = 0; j < num; j++) {
 
            // Take the second prime number
            second = primes[j];
 
            // Subtract the two prime numbers
            // from the N to obtain the third number
            third = num - first - second;
 
            // If the third number is prime
            if (binary_search(primes.begin(),
                              primes.end(), third)) {
                ans = true;
                break;
            }
        }
        if (ans)
            break;
    }
    // Print the three prime numbers
    // if the solution exists
    if (ans)
        cout << first << " "
             << second << " " << third << endl;
    else
        cout << -1 << endl;
}
 
// Driver code
int main()
{
    int n = 101;
 
    // Function for generating prime numbers
    // using Sieve of Eratosthenes
    initialize();
 
    // Function to print the three prime
    // numbers whose sum is equal to N
    findNums(n);
 
    return 0;
}

Java




// Java implementation of the approach
import java.util.*;
import java.lang.*;
import java.io.*;
 
class GFG{
 
static int MAX = 100001;
   
// The vector primes holds
// the prime numbers
static ArrayList<Integer> primes;
   
// Function to generate prime numbers
static void initialize()
{
     
    // Initialize the array elements to 0s
    boolean[] numbers = new boolean[MAX + 1];
    int n = MAX;
     
    for(int i = 2; i * i <= n; i++)
        if (!numbers[i])
            for(int j = i * i; j <= n; j += i)
             
                // Set the non-primes to true
                numbers[j] = true;
   
    // Fill the vector primes with prime
    // numbers which are marked as false
    // in the numbers array
    for(int i = 2; i <= n; i++)
        if (numbers[i] == false)
            primes.add(i);
}
   
// Function to print three prime numbers
// which sum up to the number N
static void findNums(int num)
{
    boolean ans = false;
    int first = -1, second = -1, third = -1;
     
    for(int i = 0; i < num; i++)
    {
         
        // Take the first prime number
        first = primes.get(i);
         
        for(int j = 0; j < num; j++)
        {
             
            // Take the second prime number
            second = primes.get(j);
   
            // Subtract the two prime numbers
            // from the N to obtain the third number
            third = num - first - second;
   
            // If the third number is prime
            if (Collections.binarySearch(
                primes, third) >= 0)
            {
                ans = true;
                break;
            }
        }
        if (ans)
            break;
    }
     
    // Print the three prime numbers
    // if the solution exists
    if (ans)
       System.out.println(first + " " +
                          second + " " +
                          third);
    else
        System.out.println(-1 );
}
 
// Driver code
public static void main (String[] args)
{
    int n = 101;
    primes = new ArrayList<>();
     
    // Function for generating prime numbers
    // using Sieve of Eratosthenes
    initialize();
     
    // Function to print the three prime
    // numbers whose sum is equal to N
    findNums(n);
}
}
 
// This code is contributed by offbeat

Python3




# Python3 implementation of the approach
from math import sqrt
 
MAX = 100001;
 
# The vector primes holds
# the prime numbers
primes = [];
 
# Function to generate prime numbers
def initialize() :
 
    # Initialize the array elements to 0s
    numbers = [0]*(MAX + 1);
    n = MAX;
    for i in range(2, int(sqrt(n)) + 1) :
        if (not numbers[i]) :
            for j in range( i * i , n + 1, i) :
 
                # Set the non-primes to true
                numbers[j] = True;
 
    # Fill the vector primes with prime
    # numbers which are marked as false
    # in the numbers array
    for i in range(2, n + 1) :
        if (numbers[i] == False) :
            primes.append(i);
 
# Function to print three prime numbers
# which sum up to the number N
def findNums(num) :
 
    ans = False;
    first = -1;
    second = -1;
    third = -1;
    for i in range(num) :
 
        # Take the first prime number
        first = primes[i];
        for j in range(num) :
 
            # Take the second prime number
            second = primes[j];
 
            # Subtract the two prime numbers
            # from the N to obtain the third number
            third = num - first - second;
 
            # If the third number is prime
            if (third in primes) :
                ans = True;
                break;
     
        if (ans) :
            break;
     
    # Print the three prime numbers
    # if the solution exists
    if (ans) :
        print(first , second , third);
    else :
        print(-1);
 
# Driver code
if __name__ == "__main__" :
 
    n = 101;
 
    # Function for generating prime numbers
    # using Sieve of Eratosthenes
    initialize();
 
    # Function to print the three prime
    # numbers whose sum is equal to N
    findNums(n);
 
# This code is contributed by AnkitRai01

C#




// C# implementation of the approach
using System;
using System.Collections.Generic;
class GFG
{  
  static int MAX = 100001;
 
  // The vector primes holds
  // the prime numbers
  static List<int> primes = new List<int>();
 
  // Function to generate prime numbers
  static void initialize()
  {
 
    // Initialize the array elements to 0s
    bool[] numbers = new bool[MAX + 1];
    int n = MAX;
    for (int i = 2; i * i <= n; i++)
      if (!numbers[i])
        for (int j = i * i; j <= n; j += i)
 
          // Set the non-primes to true
          numbers[j] = true;
 
    // Fill the vector primes with prime
    // numbers which are marked as false
    // in the numbers array
    for (int i = 2; i <= n; i++)
      if (numbers[i] == false)
        primes.Add(i);
  }
 
  // Function to print three prime numbers
  // which sum up to the number N
  static void findNums(int num)
  {
 
    bool ans = false;
    int first = -1, second = -1, third = -1;
    for (int i = 0; i < num; i++)
    {
 
      // Take the first prime number
      first = primes[i];
      for (int j = 0; j < num; j++)
      {
 
        // Take the second prime number
        second = primes[j];
 
        // Subtract the two prime numbers
        // from the N to obtain the third number
        third = num - first - second;
 
        // If the third number is prime
        if (Array.BinarySearch(primes.ToArray(), third) >= 0)
        {
          ans = true;
          break;
        }
      }
      if (ans)
        break;
    }
 
    // Print the three prime numbers
    // if the solution exists
    if (ans)
      Console.WriteLine(first + " " + second + " " + third);
    else
      Console.WriteLine(-1);
  }
 
  // Driver code
  static void Main()
  {
    int n = 101;
 
    // Function for generating prime numbers
    // using Sieve of Eratosthenes
    initialize();
 
    // Function to print the three prime
    // numbers whose sum is equal to N
    findNums(n);
  }
}
 
// This code is contributed by divyesh072019

Output: 

2 2 97

 

 


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!