Question: https://codility.com/demo/take-sample-test/count_factors
Question Name: Count-Factors or CountFactors
1 2 3 4 5 6 7 8 9 10 | def solution(N): candidate = 1 result = 0 while candidate * candidate < N: # N has two factors: candidate and N // candidate if N % candidate == 0: result += 2 candidate += 1 # If N is square of some value. if candidate * candidate == N: result += 1 return result |
Hi Sheng! Thanks for share your solutions!
In this one, I disagree, cause if N=1 the result should be 1 and in this solution return 0.
Just that!
I agree with your conclusion “if N=1 the result should be 1”, but disagree with “this solution return 0”. Actually this solution will return 1, if the input is 1. Please refer to the line #11.
When I run the C# version of your solution through Codility it fails timing on the last LARGE Number test case. As a result I modified it so that the multiplication isn`t performed for each loop in the while.
Nice improvement! Thanks!
Java solution
Thanks for sharing!
C# Solution – 100%
Result:
100/100/100
https://app.codility.com/demo/results/training97YW4B-RNP/
My initial approach. I treated differently odd and even numbers. Of course, one can use sqrt and avoiding additional operations. But improving that way, gave me no difference in codility tests.
I used same solution, although in Java. Only got 93% with timeout for extremely large numbers, like MAXINT. Hard to see how to improve on 0(sqaureroot(N)) time.
Actually I see now the reason for the timeout error on large numbers. The line 4 check, candidate * candidate,<N, will fail when candidate * candidate goes over MAXINT, in which case it turns negative, continuing the loop. You have to add a check for when this happens,