两个数的平方和

本文介绍了一种算法,用于找出一个整数可以如何表示为两个整数的平方和。通过使用二分查找的方法,该算法能有效地找到所有可能的表示方式,并按顺序输出。
给出一个整数N,将N表示为2个整数i j的平方和(i <= j),如果有多种表示,按照i的递增序输出。

例如:N = 130,130 = 3^2 + 11^2 = 7^2 + 9^2 (注:3 11同11 3算1种)

#include <iostream>
#include <math.h>
using namespace std;

int input[40000];
int main()
{
    int N;
    cin >> N;
    int maxVal = sqrt(N);
    for (int i = 0; i <= maxVal; i++)
    {
        input[i] = i*i;
    }
    
    int left = 0;
    int right = maxVal;
    bool found = false;
    while (left <= right)
    {
        int temp = input[left] + input[right];
        if (temp == N)
        {
            cout << left << " " << right << endl;
            found = true;
            left++;
        }
        else if (temp > N)
        {
            right--;
        }
        else
        {
            left++;
        }
    }
    
    if (!found)
    {
        cout << "No Solution" << endl;
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值