
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Find if n can be written as product of k numbers in C++
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.
Example
#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); }
Output
2, 3, 9
- Related Articles
- Check if a number can be written as sum of three consecutive integers in C++
- Count Triplets such that one of the numbers can be written as sum of the other two in C++
- Find two numbers with sum and product both same as N in C++
- Find last k digits in product of an array numbers in C++
- Product of the Last K Numbers in C++
- Find the Product of first N Prime Numbers in C++
- Find two numbers with sum and product both same as N in C++ Program
- Find ways an Integer can be expressed as sum of n-th power of unique natural numbers in C++
- Print all distinct integers that can be formed by K numbers from a given array of N numbers in C++
- Find product of prime numbers between 1 to n 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++
- Fill in the correct answer:$\sqrt{64}$ can be written as ___.
- Program to check a number can be written as a sum of distinct factorial numbers or not in Python
- Program to check n can be shown as sum of k or not in Python

Advertisements