arrow_upward

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Fastest way to prime factorize a number!!
#1
Information 
a Modification to classic sieve of eratosthenes

#include<bits/stdc++.h>
using namespace std;
void sieve(int n)
{
bool prime[n+1];
int small[n+1];
small[1]=1;
prime[1]=0;
memset(prime,1,sizeof(prime));
for(int i=2;i<=n;i++)
{
if(prime[i])
{
small[i]=i;
for(int j=i;i*j<=n;j++)
{
if(prime[j*i])
{
prime[j*i]=0;
small[j*i]=i;
}
}
}
}
for(int i=1;i<=n;i++)
cout<<small[i]<<" ";
cout<<"\n";
}
int main(void)
{
int n=20;
sieve(n);
}

here small[i] array is smallest prime factor of given index i;
It can be used to print all prime factors as follows::
void printfact(int n,int small[])
{
while(n>1)
{
cout<<small[n]<<" ";
n=n/small[n];
}
cout<<"\n";
}

Time::log n
Thanks to Post4Vps


person_pin_circle Users browsing this thread: 1 Guest(s)
Sponsors: VirMach - Host4Fun - CubeData - Evolution-Host - HostDare - Hyper Expert - Shadow Hosting - Bladenode - Hostlease - RackNerd - ReadyDedis - Limitless Hosting