[LintCode 697] Check Sum of Square Numbers(Python)

来源:互联网 发布:使用Java无法输出数值 编辑:程序博客网 时间:2024/06/16 19:55

题目描述

Given a integer c, your task is to decide whether there’re two integers a and b such that a^2 + b^2 = c.
样例
Given n = 5
Return true // 1 * 1 + 2 * 2 = 5
Given n = -5
Return false

代码

  • 法一
import mathclass Solution:    """    @param: : the given number    @return: whether whether there're two integers    """    def checkSumOfSquareNumbers(self, num):        # write your code here        if num < 0:            return False        for i in range(int(math.sqrt(num)), -1, -1):            if i * i == num:                return True            t = num - i * i            _t = int(math.sqrt(t))            if _t * _t == t:                return True        return False
  • 法二
 import mathclass Solution:    """    @param: : the given number    @return: whether whether there're two integers    """    def checkSumOfSquareNumbers(self, num):        # write your code here        if num < 0:            return False        a = 0        b = int(math.sqrt(num))        while a <= b:            if a ^ 2 + b ^ 2 == num:                return True            elif a ^ 2 + b ^ 2 > num:                b -= 1            else:                a += 1        return False
原创粉丝点击