Ask Your Question

Reliable integer root function?

asked 2015-10-31 13:42:58 -0500

Peter Luschny gravatar image

updated 2015-11-01 03:01:10 -0500

Does Sage have an integer_root(x, n) function which reliable (!) returns floor(root(x,n)) for n-th roots? I think that it should be offered as a Sage function if not.

This seems to work:

def integer_root(x, n): return gp('sqrtnint(%d,%d)' %(x,n))

Integer n-th root of x, where x is non-negative integer.

// Related: question 10730.

Edit: The answer of castor below shows a second way to define such a function:

def integer_root(x, n): return ZZ(x).nth_root(n, truncate_mode=1)[0]

Which version will be faster?

edit retag flag offensive close merge delete


This exists at least for square roots: it is called sqrtrem() and also provides the remainder.

B r u n o gravatar imageB r u n o ( 2015-10-31 14:17:20 -0500 )edit

2 answers

Sort by » oldest newest most voted

answered 2015-10-31 15:41:24 -0500

castor gravatar image

nth_root(n,truncate_mode=1) does the job, e.g. Integer(124).nth_root(3,truncate_mode=1) is (4,False)

edit flag offensive delete link more


I cannot say that I like this interface. If you want to assign the floor-integer-root you have to work around all these flags. Compare:

Simple: integer_root(2^20, 21) -> 1

Sage: ZZ(2^20).nth_root(21, truncate_mode=1) -> (1, False)

Peter Luschny gravatar imagePeter Luschny ( 2015-11-01 02:46:08 -0500 )edit

answered 2015-11-01 10:54:30 -0500

The function you are looking for is isqrt (for "integer square root").

sage: isqrt(124)

Also available as a method of integers:

sage: 124.isqrt()
edit flag offensive delete link more


Obviously this is not the function I look for as I asked for n-th roots.

Peter Luschny gravatar imagePeter Luschny ( 2015-11-01 22:09:09 -0500 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower


Asked: 2015-10-31 13:42:58 -0500

Seen: 1,099 times

Last updated: Nov 01 '15