Sort 19 Discussions, By:
Please Login in order to post a comment
Python is love, python is life.
"The square root of two is 1.41421356237309504880..., and the digital sum of the first one hundred decimal digits is 475."
The explanation can be clearer, its not first one hundred decimal digits but first one hundred digits. Decimal digits starts after the decimal point. But the answer counts all digits including the one before decimal point.
Also, set precision to higher than P, then truncate, e.g. P = 100, set precision to 110, then truncate the last 10 digits.
Man, this one is tough to get in under the wire.
For C++/Java, it seems to require:
* BigInteger (or optimized custom class for c++)
* Newton's method (faster than digit-by-digit calculation)
* Strong initial guess using double-precision sqrt
* Reducing the number of actual roots computed the long way (the final speed-up 'trick')
Even so, my Java implementation barely comes in under the wire at 3.2 s for test case 9, and C++ implementation is hit-and-miss around 2 s.
I used all those tricks including Newton's method on the inverse square root in C++. Results: case 6 in 0.96 s, case 7 in 1.68 s and case 8 and 9 time-out. Should I just hand in the Python solution or do you have a final suggestion?
optimized sum of digits of google's bigint and passed testcase 9 in 0.67 seconds using C++ (see my other comment)
You are doing right. Just optimize your multiplication and division. I was able to pass all the cases with my custom bigint class.
Finally solved this problem after a lot of efforts. Approach:
With F# (so .NET), this approach solves all test cases but the last one. With java, this exact same approach solves all test cases (test case 9 takes 3 seconds).
I'm disappointed to see that all my efforts to solve this problem in F# have failed. I see that some people managed to solve this problem with C#, so it could be that another approach than mine would be fast enough also in F#.
You only need to compute the square roots of prime numbers, because the square root of a composite number c is the product of the square roots of its prime factors.
E.g. for c=12: sqrt(12) = sqrt(2*2*3) = sqrt(2) * sqrt(2) * sqrt(3)
Actually you don't need a full factorization. Choose any two factors a and b where ab=c: sqrt(12) = sqrt(3) * sqrt(4) (or sqrt(2) * sqrt(12))
You need to be a bit careful, though: a factor can be a perfect square (such as 4), therefore memoize all (!) square roots, even the trivial ones of perfect squares. And even more, you have to increase your precision by a few digits because you'll introduce some rounding errors when multiplying. Adding 15 extra digits is more than enough.
After I added this trick to my code it became about 4x faster for N=100 and P=10000.