Search code examples
algorithmrootsquare

What is more efficient, an algorithm to calculate x^2 or one to calculate the square root of a number?


What are the more efficients algorithms to calculate x^2 and x^(1/2)? And between the best of both what is more efficient? The problem I'm trying to solve consists in find the nth 'green' number, where a N is a 'green' number if N^2 ends with n. For example 5^2=25, 376^2=141376. Here is some code I tried but takes to much time to compute the 10th number:

What I've done consist basically in take a number i of x digits obtain the last x digits of i, without making the whole power and compare this last x digits with i, if coincide sum 1 to the accumulator variable. I was thinking to avord the problem in another way, instead of calculate i^2 for every number, calculate i^(1/2) of the number and make the same comparition maybe that improve a little the program because only has to take in account the numbers that end with 0,1,4,9,6,5. But I know the really improvement come with thinking the problem in another way, of which I don't have the slightest idea.

def special_multiply(sa):
reverse_num = reversed(sa)
accumulator = 0
for i, digit in enumerate(reverse_num):
    temp_chunk = sa[i:]
    temp_pow = "".join(['1', '0' * i])
    accumulator += int(digit) * int(temp_chunk) * int(temp_pow)
return accumulator % int("".join(['1', '0' * (i + 1)]))

def green(n):
count = 0
i = 0
while count <= n:
    i += 1
    si = str(i)
    if si == str(special_multiply(si)):
        count += 1
return i

Solution

  • Put another way, a k-digit number x is green if it satisfies

     2           k
    x  = x mod 10 .
    

    The Chinese remainder theorem implies that this equation is equivalent to two equations

     2          k
    x  = x mod 2
    
     2          k
    x  = x mod 5 .
    

    Solving these equations is equivalent to finding roots of the polynomial x^2 - x = x (x - 1) modulo a power of 2 or 5. Mod 2 and mod 5, there are two solutions, namely x = 0 and x = 1. Since the derivative of the polynomial, 2x - 1 is nonzero mod 2 and mod 5 for both solutions, Hensel's lemma implies that 0 and 1 are in fact the only solutions mod the prime powers.

    Hence there are four solutions mod 10^k, which has residues 0 or 1 mod 2^k and 5^k. For example, 376 mod 5^3 = 1 and 376 mod 2^3 = 0. For each k, we can use the Chinese remainder theorem to find the four solutions (one of which will be zero and hence ineligible).