Linux安全网 - Linux操作系统_Linux 命令_Linux教程_Linux黑客

会员投稿 投稿指南 本期推荐:
搜索:
您的位置: Linux安全网 > Linux编程 > C/C PLUSPLUS > » 正文

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

来源: 未知 分享至:
问题:请使用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.



Tags:
分享至:
最新图文资讯
1 2 3 4 5 6
验证码:点击我更换图片 理智评论文明上网,拒绝恶意谩骂 用户名:
关于我们 - 联系我们 - 广告服务 - 友情链接 - 网站地图 - 版权声明 - 发展历史