I am using Trail Division Method with a pre-calculated list of primes to calculate the prime factorization of all numbers less than M (M <= 10^7).
I am using an array of vectors of pairs. The format for 10 is as follows:
PF[10][0].first = 2 // Base
PF[10][0].second = 1 // Exp
PF[10][1].first = 5
PF[10][1].second = 1
My approach is working fine but it is too slow. For M=10^7 it took 36.841 sec to compute PF of all numbers <=M on my system.
Questions
- Which is the best approach for this question?
- For my approach what other optimizations can i do?
My code
#include <iostream>
#include <fstream>
#include <vector>
#include <utility>
#include "math.h"
#include "stdio.h"
using namespace std;
const int lim=45000;
const int Max=10000000;
char prime[lim];
vector<pair <int,unsigned char> > PF[Max];
void prep()
{
//Calculation of Prime Numbers
for(int i=1;i<lim;prime[i++]=1);
for(int i=2;i*i<lim;i++)
if(prime[i])
for(int j=i+i;j<lim;prime[j]=0,j+=i);
for(int i=2;i<Max;i++) {
int num=i;
unsigned char pq=0;
//Check for powers of 2
while(num%2==0) {
pq++;
num=num/2;
}
if(pq>0)
PF[i].push_back( make_pair(2,pq) );
int pan=num;
//Loop for all primes j such that j*j<num
for(int j=3;j*j<=num;j+=2) {
if(prime[j]) {
pq=0;
while(num%j==0) {
pq++;
num=num/j;
}
if(pq>0)
PF[i].push_back( make_pair(j,pq) );
}
}
if(num>1)
PF[i].push_back( make_pair(num,1) );
}
}
main()
{
prep();
}
Timing
My Code
real 0m36.841s
user 0m36.624s
sys 0m0.265s
Igor ostrovsky Code
real 0m41.628s
user 0m41.390s
sys 0m0.265s