Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write following code in Java following example: Background A Pythagorean triplet

ID: 3749929 • Letter: W

Question

Write following code in Java following example:

Background A Pythagorean triplet is three positive whole numbers a, b, and c,such that 2+2-2. For example, (3, 4, 5) is a Pythagorean triplet, since 3 +4 5 In this project, we will refer to the sum of a Pythagorean triplet to mean the sum of those three numbers. So if a b -c,then its sum is a+b+c. So for the Pythagorean triplet (3, 4, 5), its sum is 3+4+5 12. Description You will write a Java program that will repeatedly find all Pythagorean triplets for a given sum, or find the sum that has the most Pythagorean triplets. Here is a sample run of the program (user input is in red)

Explanation / Answer

Before we procced further let us do some basic maths!
let
a = m2 -n2
b = 2*m*n
c = m2 + n2

therefore
a + b + c = m2 + 2*m*n = m * (m + 2*n) = 1000 (Since given a+b+c is 1000)
now
firstly
if m is odd;
m * (m + 2*n) becomes odd,
since 2*n + m becomes odd (even plus odd is odd) and odd multiplied by odd is odd,
so we can conclude that m is even
secondly
prime factors of 1000 are 2 and 5 and we know that
third
if m * (m + 2*n) = 1000, m is an even factor of 1000!
therefore to get all even factors of 1000 we can run a loop
for(i = 1 : count2) %note that the loop runs from 1 onwards so that m is always even
for ( j = 0: count5) %this loop runs 0 onwards since 5 is optional factor of m
m = 2^i * 5^j;

where 1000 = 2^count2 * 5^count5

if you have understood upto here the code below would be self-explanatory

tic;
p = 1000;
count2 = 0;
count5 = 0;
while (rem(p,2) == 0)
count2=count2+1;
p = p/2;
end
while (rem(p,5) == 0)
count5=count5+1;
p = p/5;
end

for(i = 1 : count2)
for ( j = 0: count5)
m = 2^i * 5^j;
if rem ((1000 - m*m),(2*m)) == 0 & (1000 - m*m)>0 %%this determines n is a Natural Number
n = (1000 - m*m)/(2*m);
if (m > n) %%m must be more than n else a would become -ve
a = m*m - n*n;
b = 2*m*n;
c = m*m + n*n;
end
end
end
end
mul = a*b*c;
timeSpent = toc;
fprintf("a*b*c = %d Time Spent = %f sec ",mul,timeSpent);

output:
a*b*c = 65625000
Time Spent = 0.000374 sec

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote