I have a code which reads around (10^5) int(s) from stdin and then after performing ## i output them on stdout. I have taken care of the INPUT part by using “setvbuf” & reading lines using “fgets_unlocked()” and then parsing them to get the required int(s).
I have 2 issues which i am not able to come over with:
1.) As i am printing int(s) 5 million on stdout its taking lot of time : IS THERE ANY WAY TO REDUCE THIS( i tried using fwrite() but the o/p prints unprintable characters due to the reason using fread to read into int buffer)
2.) After parsing the input for the int(s) say ‘x’ i actually find the no of divisors by doing %(mod) for the no in a loop.(See in the code below): Maybe this is also a reason for my code being times out:
Any suggestions on this to improved.
Many thanks
This is actually a problem from http://www.codechef.com/problems/PD13
# include <stdio.h>
# define SIZE 32*1024
char buf[SIZE];
main(void)
{
int i=0,chk =0;
unsigned int j =0 ,div =0;
int a =0,num =0;
char ch;
setvbuf(stdin,(char*)NULL,_IOFBF,0);
scanf("%d",&chk);
while(getchar_unlocked() != '\n');
while((a = fread_unlocked(buf,1,SIZE,stdin)) >0)
{
for(i=0;i<a;i++)
{
if(buf[i] != '\n')
{
num = (buf[i] - '0')+(10*num);
}
else
if(buf[i] == '\n')
{
div = 1;
for(j=2;j<=(num/2);j++)
{
if((num%j) == 0) // Prob 2
{
div +=j;
}
}
num = 0;
printf("%d\n",div); // problem 1
}
}
}
return 0;
}
//Prob 2 Is your biggesr issue right now…. You just want to find the number of divisors?
My first suggestion will be to cache your result to some degree… but this requires potentially twice the amount of storage you have at the beginning :/.
What you can do is generate a list of prime numbers before hand (using the sieve algorithm). It will be ideal to know the biggest number
Nin your list and generate all primes till his square root. Now for each number in your list, you want to find his representation as product of factors, ieThen the sum of divisors will be.
To understand you have (for n = 8)
1+ 2 + 4 + 8 = 15 = (16 - 1)/(2 - 1)It will drastically improve the speed but integer factorization (what you are really doing) is really costly…
Edit:
In your link the maximum is 5000000 so you have at most 700 primes
Simple decomposition algorithm
EDIT : rather than counting, compute
a^(n+1)usingprimepow = a; primepow = a*primepow;It will be much cleaner in C++ or java where you have hashmap. At the end
primecountcontains thepivalues I was talking about above.Even if it looks scary, you will create the
primetableonly once. Now this algorithmrun in worst case in
O(tablelen)which isO(square root(Nmax)). your initialloop ran in
O(Nmax).