import time
from math import sqrt
time.sleep(0.1) # Wait for USB to become ready

print("Hello, Pi Pico!")

def sqrt_bit_manipulation(x):
    if x < 0:
        raise ValueError("Cannot compute square root of a negative number")

    if x == 0 or x == 1:
        return x

    # Finding an initial guess by right-shifting bits
    # Start by finding the most significant bit
    bit = 1
    while bit <= x:
        bit <<= 2

    # The initial guess will have its most significant bit half of bit's position
    bit >>= 2
    result = 0
    while bit > 0:
        if x >= result + bit:
            x -= result + bit
            result = (result >> 1) + bit
        else:
            result >>= 1
        bit >>= 2

    return result


@micropython.asm_thumb
def asm_sqrt(r0):   # r0 = num
    cmp(r0,2)
    blt(LESS2)
    mov(r1,0)       # r1 = res
    mov(r2,1)       # r2 = bit

    label(start_bit)
    cmp(r2,r0)
    bgt(loop)
    lsl(r2,r2,2)    # bit <<= 2
    b(start_bit)
   
    label(loop)
    cmp(r2,0)
    beq(EXIT)
    add(r3,r1,r2)   # res + bit
    cmp(r0,r3)      # num >= res + bit
    blt(ELSE)
    sub(r0,r0,r3)   #  num -= res + bit
    asr(r1,r1,1)
    add(r1,r1,r2)   # (res >> 1) + bit
    b(CONTINUE)
    label(ELSE)
    asr(r1,r1,1)    # res >>= 1
    label(CONTINUE)
    asr(r2,r2,2)    # bit >>= 2
    b(loop)
    label(EXIT)
    mov(r0,r1)
    label(LESS2)



for i in range(10):
    print(i,sqrt_bit_manipulation(i**2),asm_sqrt(i**2))
    #print(i,asm_sqrt(i**2))
BOOTSELLED1239USBRaspberryPiPico©2020RP2-8020/21P64M15.00TTT