- Related Questions & Answers
- Check if a number can be written as sum of three consecutive integers in C++
- Find two numbers with sum and product both same as N in C++
- Find the Product of first N Prime Numbers in C++
- Count Triplets such that one of the numbers can be written as sum of the other two in C++
- Product of the Last K Numbers in C++
- Find two numbers with sum and product both same as N in C++ Program
- Find last k digits in product of an array numbers in C++
- Find product of prime numbers between 1 to n in C++
- Find ways an Integer can be expressed as sum of n-th power of unique natural numbers in C++
- C++ program to find two numbers with sum and product both same as N
- Check if a number can be expressed as a sum of consecutive numbers in C++
- C++ program to find ways an integer can be expressed as sum of n-th power of unique natural numbers
- Program to check a number can be written as a sum of distinct factorial numbers or not in Python
- Print all distinct integers that can be formed by K numbers from a given array of N numbers in C++
- Check if a number can be represented as a sum of 2 triangular numbers in C++

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

Suppose we have a number N. We have another number k. We have to check the number can be represented using k numbers or not. Suppose a number 54, and k = 3, then it will print the numbers like [2, 3, 9], if it cannot be represented, then print that.

To solve this, we will find all prime factors of N, and store them into a vector, then to find k numbers greater than 1, we check the size of the vector is greater than k or not. If size is less than k, then return -1, otherwise print first k-1 factors and the last factor will be the product of all remaining numbers.

#include<iostream> #include<vector> #include<cmath> using namespace std; int getKFactors(int n, int k){ int i; vector<int> vec; while(n % 2 == 0){ vec.push_back(2); n = n/2; //reduce n by dividing this by 2 } for(i = 3; i <= sqrt(n); i=i+2){ //i will increase by 2, to get only odd numbers while(n % i == 0){ n = n/i; vec.push_back(i); } } if(n > 2){ vec.push_back(n); } if(vec.size() < k){ cout << "Cannot be represented"; return -1; } for (int i=0; i<k-1; i++) cout << vec[i] << ", "; int prod = 1; for (int i=k-1; i<vec.size(); i++) prod = prod*vec[i]; cout << prod << endl; } int main() { int n = 54, k = 3; getKFactors(n, k); }

2, 3, 9

Advertisements