Java – Exam – Pythagorean Numbers

In this article, I will comment the original solution for the Pythagorean numbers problem from the SoftUni Java contest.


You have the following input – first a number N, telling you how many numbers you would have. Then you simply have N numbers, amongst which you should print all possible Pythagorean numbers. E.g.:



5*5 + 12*12 = 13*13
9*9 + 40*40 = 41*41
3*3 + 4*4 = 5*5

How does the code work? This time, I will first explain it and then I will show it 🙂

  1. We read “N” from the console;
  2. We initialize an int[] array nums, which is at the size of the N;
  3. With a for loop, we read N times the numbers from the console, and we assign them to the nums[];
  4. We create a HashSet! – This is something new (for me), although it was taught in the lectures. Here is a good place to read a little more about HashSets;
  5. For each int num in nums, we add a square of the num int in the HashSet;
  6. We initialize an int count and we give it 0 as a value;
  7. Here comes the important part – we have two for each loops, one for from the Pythagorean theorem and one for b, which is embedded in the first one.
  8. In the second loop, we calculate cSquare.
  9. Then we make a check whether a is smaller or equal to b && the sum of their squares is present in the HashSet.
  10. If this is the case, we generate the with a sqrt and we print in the given format.
  11. At the end, we set a counter for each Pythagorean Triple found. If the counter is zero, then we simply print “No” as an output.

Pretty much this is the whole idea of the task! It is definitely not a 20 minutes one. So, enjoy it, it is useful 🙂

Here is the code:

Tagged with: ,