[蓝桥杯2016初赛]四平方和-数论+枚举
題目描述
四平方和定理,又稱為拉格朗日定理:每個正整數(shù)都可以表示為至多4個正整數(shù)的平方和。
如果把0包括進去,就正好可以表示為4個數(shù)的平方和。
比如:
5 = 0^2 + 0^2 + 1^2 + 2^2
7 = 1^2 + 1^2 + 1^2 + 2^ 2(^符號表示乘方的意思)
對于一個給定的正整數(shù)N,可能存在多種平方和的表示法。
要求你對4個數(shù)排序:0 <= a <= b <= c <= d
并對所有的可能表示法按 a,b,c,d 為聯(lián)合主鍵升序排列,最后輸出第一個表示法
輸入
輸入存在多組測試數(shù)據(jù),每組測試數(shù)據(jù)輸入一行為一個正整數(shù)N (N<5000000)
輸出
對于每組測試數(shù)據(jù),要求輸出4個非負整數(shù),按從小到大排序,中間用空格分開
樣例輸入 Copy
5
12
773535
樣例輸出 Copy
0 0 1 2
0 2 2 2
1 1 267 838
注意點:
這題在調(diào)用sqrt()函數(shù)時要進行強制轉(zhuǎn)換,因為題目要求的四個數(shù)都是正整數(shù),如果不進行強制轉(zhuǎn)換,返回的數(shù)可能是小數(shù),就不符合要求了,如果你不知道為什么返回的是小數(shù),請點這里:
sqrt()函數(shù)的注意事項
代碼如下:
#include <iostream> #include <cmath> using namespace std; bool flag; int s;int main() {while (cin >> s) {flag = false;for (int a = 0; a * a < s; a++) {for (int b = a; b * b + a * a < s; b++) {for (int c = b; c * c + b * b + a * a < s; c++) {if (pow((int)sqrt(s - a * a - b * b - c * c), 2) == s - a * a - b * b - c * c) {cout << a << " " << b << " " << c << " " << (int)sqrt(s - a * a - b * b - c * c) << endl;flag = true;}if (flag)break;}if (flag)break;}if (flag)break;}}return 0; } #include <iostream> #include <cmath> using namespace std;int main() {int n;while(cin>>n){bool flag = false;for (int a = 0;a*a<=n;a++){for (int b = a;a*a+b*b<=n;b++){for (int c = b;c*c+b*b+a*a<=n;c++){double d = sqrt(n-a*a-b*b-c*c);if (d==int(d))//如果第4個數(shù)是整數(shù),說明符合題意{cout<<a<<" "<<b<<" "<<c<<" "<<d<<endl;flag = true;}if (flag) break;}if (flag) break;}if (flag) break;}}return 0; }總結(jié)
以上是生活随笔為你收集整理的[蓝桥杯2016初赛]四平方和-数论+枚举的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 魅族 PANDAER 35W 自带线移动
- 下一篇: [蓝桥杯2016初赛]卡片换位-bfs