1. 程式人生 > >將一個整數拆分成兩個整數的平方和演算法

將一個整數拆分成兩個整數的平方和演算法

問題:請使用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.