
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Represent a Number as a Sum of Maximum Possible Number of Prime Numbers in C++
Discuss a problem where we are given a number N, and we need to split this number in the maximum prime numbers sum, for example
Input: N = 7 Output: 2 2 3 Explanation: 7 can be represented as the sum of two 2’s and a 3 which are the maximum possible prime numbers. Input : N = 17 Output: 2 2 2 2 2 2 2 3
Approach to Find the Solution
To represent a number in prime numbers, we can subtract a prime number with N and check the difference for prime. If the difference is prime, then we can represent N as the addition of two prime numbers.
But here, we have to find a maximum number of prime numbers, and for that, we should take minimum prime numbers, i.e., 2 and 3. We can form any number with a sum of 2’s and 3’s.
Check the number of even; If it is even, it can be formed by the sum of ( N/2 ) 2’s.
It can be formed by one three and [ (N-3) / 2 ] 2’s if it is odd.
In this way, we can represent N by the sum of a maximum number of primes.
Example
#include <bits/stdc++.h> using namespace std; int main(){ int N = 7; // checking if N is odd, // If yes, then print 3 // and subtract 3 from N. if (N & 1 == 1) { cout << "3 +"; N -= 3; } // // keep subtracting and printing 2 // until N is becomes 0. while (N!=2) { cout << " 2 +"; N -= 2; } cout << " 2"; return 0; }
Output
3 + 2 + 2
Conclusion
In this tutorial, we discussed representing a number as a sum of the maximum number of prime numbers. We discussed a simple approach to solve this problem by representing numbers as a sum of 2’s and 3’s. We also discussed the C++ program for this problem which we can do with programming languages like C, Java, Python, etc. We hope you find this tutorial helpful.