|
| 1 | +""" |
| 2 | +Given an integer num_perfect_squares will return the minimum amount of perfect squares are required |
| 3 | +to sum to the specified number. Lagrange's four-square theorem gives us that the answer will always |
| 4 | +be between 1 and 4 (https://en.wikipedia.org/wiki/Lagrange%27s_four-square_theorem). |
| 5 | +
|
| 6 | +Some examples: |
| 7 | +Number | Perfect Squares representation | Answer |
| 8 | +-------|--------------------------------|-------- |
| 9 | +9 | 3^2 | 1 |
| 10 | +10 | 3^2 + 1^2 | 2 |
| 11 | +12 | 2^2 + 2^2 + 2^2 | 3 |
| 12 | +31 | 5^2 + 2^2 + 1^2 + 1^2 | 4 |
| 13 | +""" |
| 14 | + |
| 15 | +import math |
| 16 | + |
| 17 | +def num_perfect_squares(number): |
| 18 | + """ |
| 19 | + Returns the smallest number of perfect squares that sum to the specified number. |
| 20 | + :return: int between 1 - 4 |
| 21 | + """ |
| 22 | + # If the number is a perfect square then we only need 1 number. |
| 23 | + if int(math.sqrt(number))**2 == number: |
| 24 | + return 1 |
| 25 | + |
| 26 | + # We check if https://en.wikipedia.org/wiki/Legendre%27s_three-square_theorem holds and divide |
| 27 | + # the number accordingly. Ie. if the number can be written as a sum of 3 squares (where the |
| 28 | + # 0^2 is allowed), which is possible for all numbers except those of the form: 4^a(8b + 7). |
| 29 | + while number > 0 and number % 4 == 0: |
| 30 | + number /= 4 |
| 31 | + |
| 32 | + # If the number is of the form: 4^a(8b + 7) it can't be expressed as a sum of three (or less |
| 33 | + # excluding the 0^2) perfect squares. If the number was of that form, the previous while loop |
| 34 | + # divided away the 4^a, so by now it would be of the form: 8b + 7. So check if this is the case |
| 35 | + # and return 4 since it neccessarily must be a sum of 4 perfect squares, in accordance |
| 36 | + # with https://en.wikipedia.org/wiki/Lagrange%27s_four-square_theorem. |
| 37 | + if number % 8 == 7: |
| 38 | + return 4 |
| 39 | + |
| 40 | + # By now we know that the number wasn't of the form 4^a(8b + 7) so it can be expressed as a sum |
| 41 | + # of 3 or less perfect squares. Try first to express it as a sum of 2 perfect squares, and if |
| 42 | + # that fails, we know finally that it can be expressed as a sum of 3 perfect squares. |
| 43 | + for i in range(1, int(math.sqrt(number)) + 1): |
| 44 | + if int(math.sqrt(number - i**2))**2 == number - i**2: |
| 45 | + return 2 |
| 46 | + |
| 47 | + return 3 |
0 commit comments