|
-
Dec 4th, 2011, 05:31 AM
#1
Thread Starter
Fanatic Member
[RESOLVED] Calculating Number of Divisors
Hi all,
I'm currently working on project euler problem 12 and my code is working, only problem is that it is to slow.
C++ Code:
int getDivisors(int n)
{
int c = 0; // the counter
for (int i = 1; i < n; i++)
{
if (n % i == 0)
c++;
}
return c;
}
Quick explanation, It is a loop that goes from 1 to the value you gave the function and if the value divided by the Iterator is 0 it increments the counter.
this works but gets extremely slow when large digits are involved (I did a profiling test and 99.9% of my programs running time is spent in this function)
Is there a way to calculate the number of divisors of a number instead of my brute force attempt ?
-
Dec 4th, 2011, 06:11 AM
#2
Re: Calculating Number of Divisors
I would do the problem completely differently by appealing to prime factorizations. The answer appears to be n=12375, so the brute force method you're using would stall out well before then (the n=12000 case requires around 144 million runs through your loop).
You can make your brute force method much more efficient by checking for divisors only up to the square root of the number. Divisors typically come in pairs, eg. 2*6 = 12, though once in a while do not, eg. 3*3 = 9.
(I've been purposefully vague. Please ask for clarification if needed.)
The time you enjoy wasting is not wasted time.
Bertrand Russell
<- Remember to rate posts you find helpful.
-
Dec 4th, 2011, 06:14 AM
#3
Thread Starter
Fanatic Member
Re: Calculating Number of Divisors
my method actually worked after a few minutes, but now I've rewritten it and it is much Faster.
C++ Code:
int getDivisors(int n) { int c = 0; for (int i = 1; i < ceil(sqrt(n)); i++) { if (n % i == 0) c+=2; // mirror factor } return c; }
Takes about 2 seconds to do the task now
-
Dec 4th, 2011, 07:03 AM
#4
Re: [RESOLVED] Calculating Number of Divisors
I'm curious, how long did it take to run the first time? My machine took about 45 seconds to run the n=12000 to 12100 range with the inefficient method.
The time you enjoy wasting is not wasted time.
Bertrand Russell
<- Remember to rate posts you find helpful.
-
Dec 4th, 2011, 07:23 AM
#5
Thread Starter
Fanatic Member
Re: [RESOLVED] Calculating Number of Divisors
I don't really know C++ very well and I don't know how to time in C++, I could time it with my phone's stopwatch but it would be about +-500 ms wrong
-
Dec 4th, 2011, 07:43 AM
#6
Thread Starter
Fanatic Member
Re: [RESOLVED] Calculating Number of Divisors
Ok, With my first method on my computer core I5 2500 @ 3.3 ghz in C++ compiled 64 bit with the range n 12300 to 12400 it took 23.8 seconds.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|