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.:
Input |
Output |
8 41 5 9 12 4 13 40 3 |
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 🙂
- We read “N” from the console;
- We initialize an int[] array nums, which is at the size of the N;
- With a for loop, we read N times the numbers from the console, and we assign them to the nums[];
- 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;
- For each int num in nums, we add a square of the num int in the HashSet;
- We initialize an int count and we give it 0 as a value;
- Here comes the important part – we have two for each loops, one for a from the Pythagorean theorem and one for b, which is embedded in the first one.
- In the second loop, we calculate cSquare.
- Then we make a check whether a is smaller or equal to b && the sum of their squares is present in the HashSet.
- If this is the case, we generate the c with a sqrt and we print in the given format.
- 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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
import java.util.*; public class Pythagorean { public static void main(String[] args) { Scanner input = new Scanner(System.in); int n = input.nextInt(); int[] nums = new int[n]; for (int i = 0; i < nums.length; i++) { nums[i] = input.nextInt(); } HashSet squares = new HashSet<>(); for (int num : nums) { squares.add(num * num); } int count = 0; for (int a : nums) { for (int b : nums) { int cSquare = a * a + b * b; if (a <= b && squares.contains(cSquare)) { int c = (int) Math.sqrt(cSquare); System.out.printf("%d*%d + %d*%d = %d*%d\n", a, a, b, b, c, c); count++; } } } if (count == 0) { System.out.println("No"); } } } |