Double Square Problem Analysis

A double-square number is an integer which can be expressed as the sum of two perfect squares. For example, 10 is a double-square because 10 = 32 + 12. Your task in this problem is, given X, determine the number of ways in which it can be written as the sum of two squares.

For example, 10 can only be written as 32 + 12 (we don't count 12 + 32 as being different). On the other hand, 25 can be written as 52 + 02 or as 42 + 32.

Input
You should first read an integer N, the number of test cases. The next lines will contain N values of X.

Constraints
0 = = 2147483647
1 = = 100

Output

For each value of X, you should output the number of ways to write as the sum of two squares.

Solution:

int _tmain(int argc, _TCHAR* argv[])
{
	ifstream is;
	is.open("C:/in.txt");
	ofstream os;
	os.open("C:/out.txt");                  
	int N = 0;
	is >> N;
	for(int i = 0; i < N; ++i)
	{
		int X = 0;
		is >> X;
		int max = sqrt((double)X/2);     //double here 
		int rltNum = 0; 
		for(int j = 0; j <= max; ++j)
		{
			int m = j*j;
			int n = sqrt((double)X-m);
			if((m+n*n) == X)
			{
				os << "case #" << i << "(" << j << "," << n << ")" << endl;
				++rltNum;
			}
			
		}
		os << "the number of ways of case" << i << " are " << rltNum << endl;
	}
	return 0;
}

IDEA:  (1) no difference between symmetrical pair. so seperate the result set in half -> get the largest sqare root <= X/2

     (2) enumerate down from the largest square root 

      

posted @ 2013-07-25 08:20  pgu2  阅读(398)  评论(0)    收藏  举报