六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 107|回复: 0

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

[复制链接]

升级  95.33%

154

主题

154

主题

154

主题

举人

Rank: 3Rank: 3

积分
486
 楼主| 发表于 2013-2-5 01:20:13 | 显示全部楼层 |阅读模式
问题:请使用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.
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表