HNU11722 The Gougu Theorem

  原题传送:http://acm.hnu.cn/online/?action=problem&type=show&id=11722&courseid=0

  给出z,求符合方程x2 + y2 = z2的个数并输出。

  这个问题在二潘的《初等数论》中有很详细的阐述。简单来说就是:

  如果 z = i2 + j2

  那么

    x = i2 - j2

    y = 2 * i * j

View Code
 1 #include <stdio.h>
 2 #include <string.h>
 3 #include <algorithm>
 4 #include <math.h>
 5 #include <stdlib.h>
 6 #include <vector>
 7 using namespace std;
 8 typedef pair<int, int> pii;
 9 
10 int gcd(int a, int b)
11 {
12     return b == 0 ? a : gcd(b, a % b);
13 }
14 
15 int main()
16 {
17     int c, cas = 1, i, j, x, y;
18     vector<pii> v;
19     while(scanf("%d", &c), c)
20     {
21         printf("Case %d:\n", cas ++);
22         if(c % 4 != 1)
23         {
24             printf("There are 0 solution(s).\n\n");
25             continue;
26         }
27         v.clear();
28         int len = (int)sqrt(c + 0.5);
29         for(i = 1; i <= len; i ++)
30         {
31             j = (int)sqrt(c - i * i + 0.5);
32             x = j * j - i * i, y = 2 * i * j;
33             if(i < j && i * i + j * j == c && gcd(x, y) == 1 && gcd(c, x) == 1 && gcd(c, y) == 1)
34             {
35                 v.push_back(make_pair(min(j * j - i * i, 2 * i * j), max(j * j - i * i, 2 * i * j)));
36             }
37         }       
38         sort(v.begin(), v.end());
39         len = v.size();
40         printf("There are %d solution(s).\n", len);
41         for(int i = 0; i < len; i ++)
42         {
43             printf("%d^2 + %d^2 = %d^2\n", v[i].first, v[i].second, c);
44         }
45         putchar('\n');
46     }
47     return 0;
48 }

  

原文地址:https://www.cnblogs.com/huangfeihome/p/2713058.html