We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
I'm afraid that I have got the same problem. I implemented your Method "fastPowerMethod()" into my program, and it worked for "Test 1" even with the prime number 10^8+7, but it does not seem to work with 10^9+7...
Could anyone explain why? Thanks a lot!
--- edit ---
I just solved the problem myself, and it was due to "long" accidently converted to "int".
P.S. The paragraph inside the quotation marks " */ /* " is an alternate solution not using recursion.
staticintfastPowerMethod(intbase,intexponent,intmodulus){if(exponent==0){return1;}elseif(exponent%2==0){longk=fastPowerMethod(base,exponent/2,modulus);return(int)((k*k)%modulus);}else{return(int)(((long)base*(long)fastPowerMethod(base,exponent-1,modulus))%modulus);}/* int result = 1; while (exponent > 0) { if ((exponent % 2) == 1) { result = (int)(((long)result * (long)base) % modulus); } base = (int)(((long)base * (long)base) % modulus); System.out.println(exponent + ": " + result); exponent = exponent / 2; } return result; */}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Sherlock and Permutations
You are viewing a single comment's thread. Return to all comments →
I'm afraid that I have got the same problem. I implemented your Method "fastPowerMethod()" into my program, and it worked for "Test 1" even with the prime number 10^8+7, but it does not seem to work with 10^9+7... Could anyone explain why? Thanks a lot!
--- edit ---
I just solved the problem myself, and it was due to "long" accidently converted to "int". P.S. The paragraph inside the quotation marks " */ /* " is an alternate solution not using recursion.