Skip to content

Commit 3931b00

Browse files
pratyushp21abranhe
authored andcommitted
Prime Factorization C++ Program
Efficient Program to calculate all the Prime factors of a given number.
1 parent 2d001f0 commit 3931b00

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
#include<iostream>
2+
#include<vector>
3+
using namespace std;
4+
vector<int>get_factors(vector<int>&primes,int n)
5+
{
6+
vector<int>ans;
7+
ans.clear();
8+
for(int i=0;i*i<=n;i++)
9+
{
10+
if(n%primes[i]==0)
11+
{
12+
ans.push_back(primes[i]);
13+
while(n%primes[i]==0)
14+
{
15+
n=n/primes[i];
16+
}
17+
18+
}
19+
}
20+
if(n!=1)
21+
{
22+
ans.push_back(n);
23+
}
24+
return ans;
25+
}
26+
vector<int>get_prime(vector<int>&prime,int n)
27+
{
28+
for(int i=3;i<=1000;i+=2)
29+
{
30+
prime[i]=1;
31+
}
32+
//mark all the even number as non prime
33+
for(int i=3;i*i<=1000;i+=2)
34+
{
35+
if(prime[i]==1)
36+
{
37+
for(int j=i*i;j<=1000;j+=i)
38+
{
39+
prime[j]=0;
40+
}
41+
}
42+
}
43+
prime[0]=prime[1]=0;
44+
prime[2]=1;
45+
vector<int>fectors;
46+
for(int i=2;i<=1000;i++)
47+
{
48+
if(prime[i]==1)
49+
{
50+
fectors.push_back(i);
51+
}
52+
}
53+
return fectors;
54+
55+
}
56+
int32_t main()
57+
{
58+
ios_base::sync_with_stdio(false);
59+
cin.tie(NULL);
60+
//first task to genrate prime fectors and store it
61+
vector<int>p(1000,0);
62+
//now we have all prime number till n
63+
int n;
64+
cin>>n;
65+
//enter n (the number you want to get prime fector)
66+
vector<int>primes=get_prime(p,n);
67+
vector<int>ans=get_factors(primes,n);
68+
cout<<"Prime Factors are :";
69+
for(auto i:ans)
70+
{
71+
cout<<i<<" ";
72+
}
73+
cout<<endl;
74+
return 0;
75+
}

0 commit comments

Comments
 (0)