Skip to content

Instantly share code, notes, and snippets.

@corehello
Last active September 28, 2021 17:49
Show Gist options
  • Save corehello/b7c3e11191996e251e97156496772d3b to your computer and use it in GitHub Desktop.
Save corehello/b7c3e11191996e251e97156496772d3b to your computer and use it in GitHub Desktop.
nth root calculation proof of concept
def sqrtn(n, p, z):
print("sqrtn {} with {} precision is:".format(n, p))
if len(n) %z != 0:
n = "0"*(z-len(n)%z) + n
splited_n = [n[i:i+z] for i in range(0,len(n),z)]
A,B,Remainer,Result = 0,0,0,""
def get_binomial_coefficient(n,k):
if k == 0:
return 1
if k == n:
return 1
return get_binomial_coefficient(n-1, k-1) + get_binomial_coefficient(n-1, k)
def binomial_coefficients(n):
return [get_binomial_coefficient(n, k) for k in range(0,n+1)]
def findb(N, a, b, remainer, result):
for j in range(0, 11):
c = remainer*pow(10, z) + int(N)
b_cs = binomial_coefficients(z)
from functools import reduce
import operator
if reduce(operator.add,
[ pow(10, z-idx-1)*x*y for idx,(x,y) in
enumerate(zip(b_cs[1:],
[ pow(a, z-i)*pow(j, i) for i in range(1,z+1)]
))]) > c:
b = j-1
remainer = c - reduce(operator.add,
[ pow(10, z-idx-1)*x*y for idx,(x,y) in
enumerate(zip(b_cs[1:],
[ pow(a, z-i)*pow(b, i) for i in range(1,z+1)]))])
a = 10*a + b
result = "{}{}".format(result, b)
break
return a,b,remainer,result
for i in splited_n:
A,B,Remainer,Result = findb(i, A, B, Remainer, Result)
if Remainer != 0:
Result = "{}.".format(Result)
for i in ["000" for i in range(p)]:
A,B,Remainer,Result = findb(i, A, B, Remainer, Result)
return Result,A,Remainer
@corehello
Copy link
Author

> sqrtn("13310", 10, 5) # 5th root of 13310 with 10 precision
sqrtn 13310 with 10 precision is:
('6.6809098427', 66809098427, 47871672829096003837148308169945579226879093)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment