
- 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
Prime factors of a big number in C++
In this problem, we are given an integer N <= 10^18. Our task is to print all prime factors of the number along with there frequency of occurrence.
Let’s take an example to understand the problem,
Input: 100 Output: 2 2 5 2 Explanation: prime factorization of 100 = 2 * 2 * 5 * 5.
To solve this problem, we will have to find the prime factors of the number and then calculate their frequencies.
For this, we will find check the frequency of 2 as a factor and divide the number by 2. Then check from 3 to square root n. divide and increase the frequency of each prime number that is a factor of the number. And stop if the number becomes 1. Then print all primes with there frequencies.
The below code shows the implementation of our solution,
Example
#include <iostream> #include <math.h> using namespace std; void factorize(long long n){ int count = 0; while (!(n % 2)) { n/= 2; count++; } if (count) cout<<2<<"\t"<<count<<endl; for (long long i = 3; i <= sqrt(n); i += 2) { count = 0; while (n % i == 0) { count++; n = n / i; } if (count) cout<<i<<"\t"<<count<<endl; } if (n > 2) cout<<n<<"\t"<<1<<endl; } int main() { long long N = 21000; cout<<"The prime factors and their frequencies of the number "<<N<<" are \n"; factorize(N); return 0; }
Output
The prime factors and their frequencies of the number 21000 are 2 3 3 1 5 3 7 1
- Related Articles
- Maximum number of unique prime factors in C++
- C/C++ Program to find Product of unique prime factors of a number?
- Find all prime factors of a number - JavaScript
- How to find prime factors of a number in R?
- C/C++ Program to find the Product of unique prime factors of a number?
- C Program for efficiently print all prime factors of a given number?
- Product of unique prime factors of a number in Python Program
- Python Program for Product of unique prime factors of a number
- Prime factors of LCM of array elements in C++
- Print all numbers whose set of prime factors is a subset of the set of the prime factors of X in C++
- Java Program to find Product of unique prime factors of a number
- Which factors are not included in the prime factorisation of a composite number?
- Count common prime factors of two numbers in C++
- Prime factors in java
- Program to find all prime factors of a given number in sorted order in Python

Advertisements