Back to General discussions forum
Hello, I've never posted on the forum so let me know if I'm doing something wrong :)
Before I start, I just want to say that I'm really this collection of problems at code abbey. I've been doing Project Euler, but it was a little too tough for me- I was getting a little demotivated. But this site was slightly easier (but still challenging) for me-- I'm really enjoying it. I've been solving the problems as much as I can-- I love coding a LOT!
Anyway, I thought I'd challenge myself and try Problem 174.
Here's my solution so far:
'''Calculation of Pi'''
import math
def solution(inp):
'''solution(inp) -> str
solves the problem'''
K, N = map(int, inp.split(' '))
R = 10 ** K
D = R
for i in range(1, N+1):
d = D // 2
h = math.floor(math.sqrt(R ** 2 - d ** 2))
side = math.floor(math.sqrt(d ** 2 + (R - h) ** 2))
D = side
return str(6 * (2 ** N) * side // 2)
print(solution(input()))
Unfortunately, the test cases was not passed. I seem to be off of the answer-- expected answer-- 3141592653589793238460697950840992021960143818156051595126259056640 -- my answer -- 3141592653590214394663976101301052353379622232312789468965320523776.
I appreciate any help-- a nudge in the right direction would be greatly appreciated.
Thanks for the formation of this marvelous community!
P.S. I already tried changing math.floor(math.sqrt()) to math.isqrt(), but then when I try to run it in the sandbox, I get an Attribute Error saying that 'math' has no attribute 'isqrt'. Maybe it isn't supposed to be used?
The sandbox is running a slightly older version of Python that does not have isqrt
.
Since the point of the problem is to run an entirely integer-based computation, perhaps int(math.sqrt())
would work better than math.floor(math.sqrt())
? There's no guarantee that the rounding error won't creep in, of course.
To avoid those, you can build your own isqrt
if you want to run in the sandbox. Or, even more simply, you can run your code on your local machine.
Hello zelevin! First off, thanks for taking the time to respond and assist me in this problem!
I initialy used int(math.sqrt())
but errors still came. Then I tried math.floor(math.sqrt())
but the same problem occured.
I just ran isqrt
on my machine and it worked! I thought that if it's not implemented in the sandbox, we're not supposed to use it. Thanks for clarifying that it's okay to just run on my local machine.
I really appreciate your assistance, thanks again!