以下是使用C++实现四平方和定理的代码示例:

#include <iostream>
#include <cmath>
using namespace std;

void four_square_sum(int n) {
    int a, b, c, d;
    for (a = 0; a <= sqrt(n/4); a++) {
        for (b = a; b <= sqrt((n-a*a)/3); b++) {
            for (c = b; c <= sqrt((n-a*a-b*b)/2); c++) {
                d = sqrt(n-a*a-b*b-c*c);
                if (a*a+b*b+c*c+d*d == n) {
                    cout << "The four squares are: " << a << "^2 + " << b << "^2 + " << c << "^2 + " << d << "^2" << endl;
                    return;
                }
            }
        }
    }
    cout << "No solution found." << endl;
}

int main() {
    int n;
    cout << "Enter a positive integer: ";
    cin >> n;
    four_square_sum(n);
    return 0;
}

该程序首先接受一个正整数n作为输入,并使用三重循环来查找四平方和解。循环变量a、b、c、d分别代表四个平方数,它们的范围由数学公式确定。如果找到了符合条件的解,则输出结果。如果没有找到解,则输出一个提示信息

所有四平方和定理c++

原文地址: https://www.cveoy.top/t/topic/fDjw 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录