python 最小平方函数

6fe3ivhb  于 2022-12-02  发布在  Python
关注(0)|答案(2)|浏览(153)

考虑一个正整数n。如果我们把n的数字和k的数字连接起来,我们得到一个完美的平方,那么最小的数k是多少?
例如,对于n=1,最小的k是6,因为16是完美的正方形。
对于n=4,k必须为9,因为49是一个完美的正方形。
对于n=35,k为344,因为35344=1882是从数字35开始的最小完全正方形。
定义smallestSquare函数,该函数接受正整数n,并返回最小整数k,其n,k的数字连接产生一个完美的正方形。
现在我所知道的就是这个,它检查给定的数是否是一个完美的平方。我想用递归来解决这个问题,但我甚至不知道从哪里开始。

from math import sqrt

def isSquare(n):
  return n == int(sqrt(n) + 0.5) ** 2
  
def smallestSquare(n):
eufgjt7s

eufgjt7s1#

不需要递归:

def smallestSquare(n):
    x = 1
    while isSquare(int(str(n)+str(x))) == False:
        x += 1
    return int(str(n)+str(x))
wtlkbnrh

wtlkbnrh2#

如果给定某个数字'n',您要寻找以'n'开头的最小完美suqare,下面是一个可行的方法:

import math

def find_smallest_perfect_square(start: int) -> int:
    while True:
        if int(math.sqrt(start)) != math.sqrt(start):
            start += 1
        else:
            return start
        
def find_concatenation(n: int) -> int:
    str_n = str(n)
    while True:
        val = find_smallest_perfect_square(n)
        if str(val).startswith(str_n):
            return val
        else:
            n = val + 1

测试:

for i in range(10):
    print (f'The smallest perfect square that begins with {i} is {find_concatenation(i)}')

# Result:
    # The smallest perfect square that begins with 0 is 0
    # The smallest perfect square that begins with 1 is 1
    # The smallest perfect square that begins with 2 is 25
    # The smallest perfect square that begins with 3 is 36
    # The smallest perfect square that begins with 4 is 4
    # The smallest perfect square that begins with 5 is 529
    # The smallest perfect square that begins with 6 is 64
    # The smallest perfect square that begins with 7 is 729
    # The smallest perfect square that begins with 8 is 81
    # The smallest perfect square that begins with 9 is 9

如果你要找的是“k的最小值”,当它与n连接时,会产生一个完美的平方--上面的方法不能保证给予你你想要的。如果这是你所需要的,请说明。

相关问题