Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added seive #483

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions Algorithms/C++/prime_factorization_using_sieve.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/*
Prime Factors [1,n]
while( num ! = 1 ):

We keep on dividing it with its smallest prime factor.

The smallest prime factor is pre-calculated using a slightly modified prime sieve.
Since we start from 2 and go on, we mark the first multiple as the spf.
Preprocessing for Sieve: O(n log log n)
Time Complexity for factorization: O(log n)
Space Complexity: O(n)
*/
#include <bits/stdc++.h>
using namespace std;

void pfsieve(int n)
{
int spf[n + 1];
for (int i = 2; i <= n; i++)
{
spf[i] = i;
}

for (int i = 2; i <= n; i++)
{
if (spf[i] == i)
{
for (int j = i * i; j <= n; j += i)
{
if (spf[j] == j)
{
spf[j] = i;
}
}
}
}
while (n != 1)
{
cout << spf[n] << " ";
n = n / spf[n];
}
}

int main()
{
int n;
cin >> n;
pfsieve(n);
return 0;
}