COMP2113
COMP2113_ENGG1340 Programming technologies and Computer programming II [Section 2BC] [2023]
Loading...
Searching...
No Matches
3.cpp
Go to the documentation of this file.
1
//eric15342335
2
//problem 3
3
//Write a C++ program which takes one user input integer n (0 ≤ n ≤ 100000),
4
//and find all right-angled triangles with
5
//integer side lengths whose perimeter is n
6
#include <iostream>
7
using namespace
std;
8
9
int
main
(){
10
int
n,a,b,c;
11
cin >> n;
12
// given a+b+c=n and a<=b<=c
13
// a+b>=c (triangle inequality)
14
// a+b+c>=2c (add c)
15
// c<=n/2 (obtain an upper bound of c)
16
17
// since a*a+b*b=c*c therefore b*b<c*c b<c
18
// assume a=b, then 2a*a=c*c, c=sqrt(2)*a
19
// where c is not an integer, contradicts "int c" requirement
20
// therefore a<=b can be simplified as a<b
21
22
// assume b=c, then a*a=0 -> a=0 (rej.)
23
// .'. b<=c can be simplifies as b<c
24
// a+b+c=n -> 3c>n -> c>n/3
25
26
// since c<=n/2 -> n-c>=n/2
27
// a+b+c=n -> 2b>n-c -> b>n/4
28
29
// we want output sort in ascending order of a
30
// b+c=n-a -> 2b<n-a, when a increase b decrease
31
// a+c=n-b -> 2c>=n-b, when b decrease c decrease
32
// which means descending order of b and c
33
for
(c=n/2;c>n/3;c--){
34
for
(b=c-1;b>n/4;b--){
35
a=n-c-b;
36
// since the lower bound of b and c are too small, check a<b<c
37
if
((a*a+b*b==c*c) && (a<b) && (b<c)){
38
cout << a <<
" "
<< b <<
" "
<< c <<
"\n"
;
39
}
40
}
41
}
42
return
0;
43
}
main
int main()
Definition
3.cpp:9
Assignment1
3.cpp
Generated on Sun Sep 29 2024 16:39:53 for COMP2113 by
1.12.0