Find three prime numbers with given sum
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 13Input: 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 numbersvector<int> primes;// Function to generate prime numbersvoid 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 Nvoid 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 codeint 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 approachimport java.util.*;import java.lang.*;import java.io.*;class GFG{static int MAX = 100001; // The vector primes holds// the prime numbersstatic ArrayList<Integer> primes; // Function to generate prime numbersstatic 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 Nstatic 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 codepublic 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 approachfrom math import sqrtMAX = 100001;# The vector primes holds# the prime numbersprimes = [];# Function to generate prime numbersdef 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 Ndef 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 codeif __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 approachusing 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 |
2 2 97
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.


