234234234

[蓝桥杯2016初赛]四平方和

以下几种解法:

参考博客

https://blog.csdn.net/Tianweidadada/article/details/79748074

 

一、暴力:

#include <iostream>
#include <cmath>
#include <algorithm>
#define N 5000009

using namespace std;

int main() {
    int n;
    int ans[4];
    int flag;
    while(cin >> n) {
        flag = 1;
        int max = sqrt(n);
        cout << max << endl;
        for (int a = 0; a <= max && flag;a++)
            for (int b = 0; b <= max && flag;b++)
                for (int c = 0; c <= max && flag;c++)
                    for (int d = 0; d <= max && flag;d++) {
                        if (a*a + b*b + c*c + d*d == n) {
                            ans[0] = a;
                            ans[1] = b;
                            ans[2] = c;
                            ans[3] = d;
                            flag = 0;
                        }
                    }
        sort(ans, ans+4);
        cout << ans[0] << " ";
        cout << ans[1] << " "; 
        cout << ans[2] << " "; 
        cout << ans[3] << endl;
    }
    return 0;
}
View Code

 

二、(参考的博客)

#include <iostream>
#include <cmath>
#include <algorithm>
#define N 5000009

using namespace std;

int main() {
    int n;
    int ans[4];
    int flag;
    while(cin >> n) {
        flag = 1;
        int max = sqrt(n);
        for (int a = 0; a <= max && flag;a++)
            for (int b = 0; b <= max && flag;b++)
                for (int c = 0; c <= max && flag;c++) {
                    int s = n - (a*a + b*b + c*c);
                    double l = sqrt((double) s);//第二次技巧
                    if(l == (int)l ) {
                        ans[0] = a;
                        ans[1] = b;
                        ans[2] = c;
                        ans[3] = l;
                        flag = 0;
                    }
                }
        sort(ans, ans+4);
        cout << ans[0] << " ";
        cout << ans[1] << " "; 
        cout << ans[2] << " "; 
        cout << ans[3] << endl;
    }
    return 0;
}
View Code

 

posted @ 2020-07-03 22:31  你若愿意,我一定去  阅读(156)  评论(0编辑  收藏  举报
23423423423