Path: csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!feeder.erje.net!eu.feeder.erje.net!newsfeed.xs4all.nl!newsfeed2.news.xs4all.nl!xs4all!post.news.xs4all.nl!not-for-mail Return-Path: X-Original-To: python-list@python.org Delivered-To: python-list@mail.python.org X-Spam-Status: OK 0.001 X-Spam-Evidence: '*H*': 1.00; '*S*': 0.00; 'algorithm': 0.04; 'inspired': 0.05; 'root': 0.05; 'sys': 0.07; 'calculating': 0.09; 'received:80.91': 0.09; 'received:80.91.229': 0.09; 'received:gmane.org': 0.09; 'received:list': 0.09; 'def': 0.12; 'math,': 0.16; 'received:80.91.229.3': 0.16; 'received:plane.gmane.org': 0.16; 'true:': 0.16; 'valueerror': 0.16; 'wrote:': 0.18; 'import': 0.22; 'header:User-Agent:1': 0.23; 'integer': 0.24; 'header:X-Complaints-To:1': 0.27; 'header:In- Reply-To:1': 0.27; 'raise': 0.29; "d'aprano": 0.31; 'steven': 0.31; 'there': 0.35; 'positive': 0.37; 'to:addr:python-list': 0.38; 'to:addr:python.org': 0.39; 'received:org': 0.40; 'charset:windows-1252': 0.65; 'received:46': 0.66; 'here': 0.66; 'optimized': 0.68; 'square': 0.74; 'ideas.': 0.84 X-Injected-Via-Gmane: http://gmane.org/ To: python-list@python.org From: Serhiy Storchaka Subject: Re: Challenge: optimizing isqrt Date: Thu, 20 Nov 2014 20:00:04 +0200 References: <54543787$0$13005$c3e8da3$5496439d@news.astraweb.com> Mime-Version: 1.0 Content-Type: text/plain; charset=windows-1252; format=flowed Content-Transfer-Encoding: 7bit X-Gmane-NNTP-Posting-Host: 46.211.151.127 User-Agent: Mozilla/5.0 (X11; Linux i686; rv:31.0) Gecko/20100101 Thunderbird/31.0 In-Reply-To: <54543787$0$13005$c3e8da3$5496439d@news.astraweb.com> X-BeenThere: python-list@python.org X-Mailman-Version: 2.1.15 Precedence: list List-Id: General discussion list for the Python programming language List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Newsgroups: comp.lang.python Message-ID: Lines: 34 NNTP-Posting-Host: 2001:888:2000:d::a6 X-Trace: 1416506494 news.xs4all.nl 2937 [2001:888:2000:d::a6]:49605 X-Complaints-To: abuse@xs4all.nl Xref: csiph.com comp.lang.python:81100 On 01.11.14 03:29, Steven D'Aprano wrote: > There is an algorithm for calculating the integer square root of any > positive integer using only integer operations: Here is my optimized implementation inspired by Christian's ideas. import math, sys C1 = sys.float_info.radix ** sys.float_info.mant_dig C2 = int(sys.float_info.max) C3 = C2.bit_length() - 2 def isqrt(n): if n < 0: raise ValueError if n == 0: return 0 if n <= C1: return int(math.sqrt(n)) if n <= C2: x = int(math.sqrt(n)) else: b = (n.bit_length() - C3) // 2 x = int(math.sqrt(n >> (2 * b))) << b y = (x + n // x) // 2 if y == x: return x while True: x = y y = (x + n // x) // 2 if y >= x: return x