将一个整数拆分成两个整数的平方和算法

问题:请使用C/C++写一个程序实现将一个整数拆分成两个整数的平方和,把所有的可能的组合都要计算出来。

答:假定输入的整数为n,则扫描1-(n的平方根)之间的整数,令row=1,column=(int)(sqrt((double)given)+0.5),使得row*row+column*column=n的数输出即可。

代码如下所示:



//
// main.cpp
// MyProjectForCPP
//
// Created by labuser on 11/2/11.
// Copyright 2011 __MyCompanyName__. All rights reserved.
//

#include <iostream>
#include <math.h>

using namespace std;


int main (int argc, const char * argv[])
{
int given;
int row,column;
int count;
char line[100];

printf("\nRepressenting a Given Number as the the Sum of Two Squares");
printf("\n==========================================================\n");
printf("\nAn Integer Please ---> ");
gets(line);

given = atoi(line);
printf("\nCount X Y");
printf("\n------ ----- ------");

row =1;
column=(int)(sqrt((double)given)+0.5);
while (row<=given && column>0) {
if(row*row+column*column==given){
++count;
printf("\n%5d%7d%7d",count,row,column);
++row;
--column;
}
else if(row*row+column*column>given)
{
--column;
}else{
++row;
}
}

if(count==0){
printf("\n\nSorry, NO ANSWER found.");
}else{
printf("\n\nThere are %d possible answers.\n",count);
}

return 0;
}




运行结果:
Repressenting a Given Number as the the Sum of Two Squares
==================================================
An Integer Please ---> 200

Count X Y
------ ----- ------
1 2 14
2 10 10
3 14 2

There are 3 possible answers.
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值