简体   繁体   中英

number which is Square or can be written as sum of two squares python

I created a program in python to check if a given number is square or can be written as sum of two squares, but it doesn't work.please help me.

def sum(num):
    def m(a):
        b=a
        for item in range(a):
            b=b-1
            if a==b*b:
                return(a)
    c=num
    for item in range(1,num):
        c-=1
        if m(c)==c and m(d)==d:
            print(num)

you can check if something is a perfect square if the int of its square root squared is its target

def is_square(n):
    return int(n**0.5)**2 == n

the second part is a little harder (though not hard)

first you only need to check ints up to the square root of the target and then add 1

for i in range(0,int(target**0.5+1)):

then you need to go over the remaining numbers you can get teh remaining numbers with

    for j in range(i,int((target-i**2)**0.5+1)

then all you have to do is check if i squared + j squared is your target if it is than i,j is one of your solutions

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM