MATLAB A Pythagorean triplet is a set of three natural numbe
MATLAB
A Pythagorean triplet is a set of three natural numbers, aSolution
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

