Python Coding Challenge - Sum of Squares

Here’ a fun Python challenge involving just a bit of mathematical know-how:

Write a function that takes an argument n and prints a pair of natural numbers x, y such that x² + y² = n

For the purposes of this exercise we will assume that n > 0. So, for example: for n = 10, we can have 1² + 3² = 10, so x = 1 and y = 3.

There is a relationship between this problem and the famous Pythagorean Theorem, which is one of the most important pieces of mathematical knowledge ever discovered. It underpins numerous aspects of the technological world we live in, and it’s also very useful in games for calculating the distance between things. You can read more about that here: How to calculate the distance between two points with Python, and a fun game to play.

Here’s a couple of observations which may help you:

  • In Python to calculate the square root of n, we can use math.sqrt(n)
  • Since n > 0, x must be at least 1.
  • Since x >= 1, y can be at most √(n – 1)
  • Let’s assume x <= y, as otherwise we would have duplicate solutions (e.g. 1² + 3² = 10 and 3² + 1² = 10)
  • In Python one way to square a number is to use ** 2. E.g 3 ** 2 = 9
  • There is a useful function math.floor(n), which gives the greatest integer less than or equal to n
  • This is useful because e.g for n = 3, 1² + (√3)² rounded up would be too large. So we use math.floor(math.sqrt(n)) as the upper possible value for x or y
  • You may want to read up on nested FOR loops to help you with this challenge

Have a go at completing the above code for yourself using your favorite Python development environment. The assert statements are just a simple way to test your code – when it is correct, nothing will happen, which is a good thing, but if an assertion is not true, you will get an AssertionError. If this is not clear and you would rather not use assert, you can delete those statements and just use print statement instead. E.g. print(sum_of_squares(10)).

Solution to Python Sum of Two Squares Challenge

Click below for one way to solve the challenge.

I hope you found that to be an intersting Python coding challenge. All the time you spend thinking how to solve these kinds of problems with make you a better Python programmer. Happy computing.

Leave a Reply

Your email address will not be published. Required fields are marked

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}