Python算法——完美平方

20200322_Python_算法

小菜鸟算法历险记(一)

题目:完美平方

1、问题描述:
给定一个正整数n,找到若干个完全平方数(例如:1,4,9,…),使得它们的和等于n,完全平方数的个数最少

2、问题示例:
给出 n = 12 ,返回 3 , 因为 12 = 4 + 4 + 4 ;给出 n = 13 , 返回 2,因为 13 = 4 + 9。

3、代码实现:

# 参数 n 是一个正整数,这点很重要,以后做算法题一定先看好输入是什么类型的数
# 返回 是一个整数
class Solution:
	def numSquares(self, n):
		while n % 4 == 0:  # 用4
			n //= 4
		if n % 8 == 7:  #7 = 4 + 1 + 1 + 1 
			return 4  
		for i in range(n + 1):
			temp = i * i
			if temp <= n:
				if int((n - temp) ** 0.5) ** 2 + temp == n:
					return 1 + (0 if temp == 0 else 1)
			else:
				break
		return 3
# 主函数
if __name__== '__main__' :
	n = 12
	print("初始值:", n)
	solution = Solution()
	print("结果:", solution.numSquares(n))

4、运行结果:
初始值:12
结果:3

5、后面,为了更清楚的观察过程,Solution类的代码改为:

class Solution:
    def numSquares(self, n):
        while n % 4 == 0:
            n //= 4
        if n % 8 == 7:
            return 4
        for i in range(n + 1):
            temp = i * i
            print("temp", temp)
            if temp <= n:
                a = (n - temp)
                print("a", a)
                b = int(a ** 0.5) ** 2
                print("b", b)
                if b + temp == n:
                    return 1 + (0 if temp == 0 else 1)
            else:
                break
        return 3

6、输出结果:

初始值: 13
temp 0
a 13
b 9
temp 1
a 12
b 9
temp 4
a 9
b 9
结果: 2

很神奇的设计思路…,大家有更好的理解麻烦一起讨论一下!谢谢

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值