I'm working on problem 12 in relation to the first triangle number with 500 separator. I tried to solve brute force, I get 300 dividers in about 350 seconds and can not get 400 in 10 minutes. I will change my solution to use the most important factor method, but now I have seen that people are still getting this solution with animals within a minute.
Can you please criticize my code and tell me if I am missing something so that it is very inefficient?
Unsigned long triangle numeric target (int divisor target) {unsigned long triangle new = 1; Unsigned long running nun = 2; Int numOfDivisors = 0; NumOfDivisors = NumOfDivisors (triangleNum); While (numOfDivisors & lt; divisorTarget) {triangleNum + = currentNum; CurrentNum ++; NumOfDivisors = NumOfDivisors (triangleNum); } Return triangle Nome; } NAMOF divisors (unsigned long-term dividend) {int NudivIizer = 0; Set & lt; Unsigned long long & gt; Divisors; Set & lt; Unsigned long & gt; :: Iterator; (Unsigned long time index = 1; index & lt; = dividend / 2; index ++) {if (dividend% index == 0) {divisors.insert (index); NumDivisors ++; This is = divisors.find (dividend / index); If (this == divisors.end ()) {divisors.insert (dividends / index); NumDivisors ++; } / * Is not checking for dups above for some reasons and just how many items are being checked in the end (this is = divisors.begin () =); = Divisors.end (); This ++) {numDivisors ++; } * /}} Return Number Divisors; } Int main () {cout & lt; & Lt; Trianglenumber divisors (500) & lt; & Lt; Endl; Return 0; }
Update: Now understand it, thank you. The square root of the number was changed to check, and checked an additional to see if it was a perfect square. This allowed me to completely remove the set. 500 Devices ran in 12 seconds.
You are currently dividend / 2
for the separator. You can lower it on sqrt (dividends)
, which is asymptotically fast if a dividend
class is required then a special case may be required.
My C ++ code for the problem is 12 (which is basically the same as yours, but it uses the lower limit, and it also means that instead of dividis Instead) about 1 second
Comments
Post a Comment