18051 勾股数
18051 勾股數
Description
若三個正整數a、b、c,其中a<=b<=c,滿足a2+b2=c2表示上標,稱這三個數為“勾股數”,例如:3、4、5是勾股數。編程輸出不大于n的所有勾股數。
輸入格式
輸入一個數(n<=100)
輸出格式
輸出所有勾股數,按第1個數字由小到大排列(若第1個數字相同,按第2個數字排)
輸入樣例
16
輸出樣例
3 4 5
5 12 13
6 8 10
9 12 15
注意輸出要求!因此大循環是從a開始,后面的每層初始 = a
正確代碼1:三層循環嵌套
#include <iostream> #include <cstdio> #include <math.h>using namespace std;int main() {int n;cin >> n;for(int a = 1;a <= n;a++){for(int b = a;b <= n;b++){for(int c = b;c <= n;c++){if(a * a + b * b == c * c){cout << a << " " << b << " " << c << endl;}}}}return 0; }正確代碼2:兩層循環嵌套,c用公式求得
#include <iostream> #include <cstdio> #include <math.h>using namespace std;int main() {int n,a,b,c;cin >> n;for(a = 1;a <= n;a++){for(b = a;b <= n;b++){c = (int)sqrt(a * a + b * b);if(a * a + b * b == c * c && c <= n){cout << a << " " << b << " " << c << endl;}}}return 0; }錯誤代碼:輸出是按照c從小到大,不符題意
#include <iostream> #include <cstdio> #include <math.h>using namespace std;int main() {int n;cin >> n;for(int a = 1;a <= n;a++){for(int b = 1;b <= a;b++){for(int c = 1;c <= b;c++){if(a * a == b * b + c * c){cout << c << " " << b << " " << a << endl;}}}}return 0; }總結
- 上一篇: TortoiseSVN 汉化
- 下一篇: dvajs项目要部署到服务器上,dvaJ