leetcode -. 633 and the number of square

After more than 40 minutes just to write out questions should still be thinking.

But I am very happy by the

 1 class Solution:
 2     def judgeSquareSum(self, c: int) -> bool:
 3         if c==0:
 4             return True
 5         
 6         i=int((c//2)**0.5)
 7         j=int((c//2)**0.5)+1
 8         while i<int(c**0.5)+1 and j>=0:
 9             if i**2+j**2==c:
10                 return True
11             elif i**2+j**2>c:
12                 j=j-1
13             elif i**2+j**2<c:
14                 i=i+1
15         else:
16             return False
When execution: 940 ms, beat the 5.23% of users in all Python3 submission
Memory consumption: 13.8 MB, beat the 8.44% of users in all Python3 submission
 
for example:
If c = 78
Because c 2 is greater than 8 **, 9 ** less than 2,
So when traversing the maximum size of i is 8. Because it is two square numbers and so is the fairest i ** 2 and j ** 2 each accounted for c / 2.
Therefore, the start value of i is the square root of the c / 2 start to the end of the root c;
j started, gradually decreases from the root of 2 / c + 1, 0 to end.
As well as the determination condition traversal routine shown
 
I actually do not understand this. . . . . .
And then found, I do not understand because I do not know this theorem:
'' 'Theorem: is a positive integer and the sum of two squares, if and only if all 4k + 3 type prime factors are even-numbered power of the positive integer. It can be any positive integer factorization as c = (2 ^ r) * (p1 ^ n1) * (p2 ^ n2) * ... * (pk ^ nk), where p1 ... pk is a prime factor, n1. ..nk the power of a factor. That is a prime factor of the form pi 4k + 3, if ni is an odd number, then it can not be written as a sum of two squared integers a and. '' '
 
 
Code first step is to remove all 2, do prime factorization :
if c <= 2:
            return True
        while c % 2 == 0:
            c = c // 2

Do while factorization, determine the type and power of a prime factor :

p = 3
        while p * p <= c:
            index = 0
            while c % p == 0:
                index += 1
                c = c // p
            if (p % 4 == 3) and (index % 2 == 1):
                return False
            p += 2

# Decomposition to the final c is actually a prime number, this time if it is judged c is shaped such primes 4k + 1, it certainly can be written as two integer sum of squares (may be judged not to be shaped as a prime number 4k + 3 too) this is not thoroughly understand. . .

return c % 4 == 1

This idea, like me, but I write more than simple and refreshing.

while i <= j:
            total = i * i + j * j

This is a great job with.

That's the difference ah, obviously also thought, but he sent a furnace

                                                                                     ——2019.9.25
 

 

Guess you like

Origin www.cnblogs.com/taoyuxin/p/11584096.html