From 529fc1843edf7059993a1397e49456365ab3f38e Mon Sep 17 00:00:00 2001 From: akhem301 Date: Sat, 28 Oct 2017 02:01:19 +0530 Subject: [PATCH] Prime Factorization of a number --- Math/Prime_Factorization/README.md | 10 +++ .../primefactorization.cpp | 71 +++++++++++++++++++ 2 files changed, 81 insertions(+) create mode 100644 Math/Prime_Factorization/README.md create mode 100644 Math/Prime_Factorization/primefactorization.cpp diff --git a/Math/Prime_Factorization/README.md b/Math/Prime_Factorization/README.md new file mode 100644 index 000000000..9d9cd83a4 --- /dev/null +++ b/Math/Prime_Factorization/README.md @@ -0,0 +1,10 @@ +Prime Factorization is a very important and useful technique to factorize any number into its prime factors. It has various applications in the field of number theory. + +The method of prime factorization involves two function calls. +First: Calculating all the prime number up till a certain range using the standard + Sieve of Eratosthenes. + +Second: Using the prime numbers to reduce the the given number and thus find all its prime factors. + +The complexity of the solution involves approx. O(n logn) in calculating sieve of eratosthenes +O(log n) in calculating the prime factors of the number. So in total approx. O(n logn). diff --git a/Math/Prime_Factorization/primefactorization.cpp b/Math/Prime_Factorization/primefactorization.cpp new file mode 100644 index 000000000..8a17badd7 --- /dev/null +++ b/Math/Prime_Factorization/primefactorization.cpp @@ -0,0 +1,71 @@ +#include +using namespace std; + +// Declaring variables for maintaing prime numbers and to check whether a number is prime or not +bool isprime[1000006]; +vector prime_numbers; +vector > factors; + +// Calculating prime number upto a given range +void SieveOfEratosthenes(int N) +{ + memset(isprime, true, sizeof isprime); + + for(int i=2; i<=N ;i++) + { + if(isprime[i]) + { + for(int j=2*i; j<=N; j+=i) + isprime[j]=false; + } + } + + for(int i=2;i<=N;i++) + { + if(isprime[i]) + prime_numbers.push_back(i); + } + + return; +} + +// Prime factorization of a number +void prime_factorization(int num) +{ + for(int i=0; prime_numbers[i]<=num; i++) + { + int count=0; + + while(num%prime_numbers[i] == 0) + { + count++; + num = num/prime_numbers[i]; + } + + if(count) + factors.push_back(make_pair(prime_numbers[i],count)); + } + + if(num>2) + factors.push_back(make_pair(num,1)); + + return; +} + +int main() +{ + int num; + cin>>num; + + SieveOfEratosthenes(num); + + prime_factorization(num); + + // Prime factors with their powers in the given number in new line + for(auto it: factors) + { + cout<