Language:
Fermat vs. Pythagoras
Description
Computer generated and assisted proofs and verification occupy a small niche in the realm of Computer Science. The first proof of the four-color problem was completed with the assistance of a computer program and current efforts in verification have succeeded in verifying the translation of high-level code down to the chip level.
This problem deals with computing quantities relating to part of Fermat's Last Theorem: that there are no integer solutions of a^n + b^n = c^n for n > 2. Given a positive integer N, you are to write a program that computes two quantities regarding the solution of x^2 + y^2 = z^2, where x, y, and z are constrained to be positive integers less than or equal to N. You are to compute the number of triples (x,y,z) such that x < y < z, and they are relatively prime, i.e., have no common divisor larger than 1. You are also to compute the number of values 0 < p <= N such that p is not part of any triple (not just relatively prime triples). Input
The input consists of a sequence of positive integers, one per line. Each integer in the input file will be less than or equal to 1,000,000. Input is terminated by end-of-file
Output
For each integer N in the input file print two integers separated by a space. The first integer is the number of relatively prime triples (such that each component of the triple is <=N). The second number is the number of positive integers <=N that are not part of any triple whose components are all <=N. There should be one output line for each input line.
Sample Input 10 25 100 Sample Output 1 4 4 9 16 27 Source |
题意:求1~n之间x^2+y^2=z^2且x,y,z互素有多少组,和不含x^2+y^2=z^2的数的个数。
分析:刚学数论,该式子的x,y,z构成毕达哥拉斯三元组,其中两两互素的成为本原毕达哥拉斯三元组,对于本原毕达哥拉斯三元组有一个构造定理:当且仅当y为偶数且存在两个正整数m和n互素,m和n奇偶互异则
x = m*m-n*n
y = 2*m*n;
z = m*m+n*n; (x, y, z)为本原毕达哥拉斯三元组
对于本题最多枚举到√n即可时间复杂度为(n*k)k为询问次数,本题还卡空间,刚开始MLE了,需要优化一下
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <cctype>
#include <algorithm>
using namespace std;
const int maxn = 1000000 + 5;
int p[maxn];
bool vis[maxn];
int gcd(int a, int b)
{
return b == 0 ? a : gcd(b, a%b);
}
void query(int num)
{
p[0] = 0;
int sum = 0;
memset(vis, 0, sizeof(vis));
memset(p, 0, sizeof(p));
int mmax = (int)sqrt(1.0*num);
for (int m = 1; m <= mmax; m++)
{
for (int n = 1; n < m; n++)
{
if (gcd(m, n) != 1) continue;
if ((m%2==0&&n%2==0)||(n%2==1&&m%2==1)) continue;
int x = m*m-n*n;
int y = 2*m*n;
int z = m*m+n*n;
if (z <= num)
{
sum++;
vis[x] = 1;
vis[y] = 1;
vis[z] = 1;
for (int j = 2; z*j <= num; j++)
{
vis[j*x] = 1;
vis[j*y] = 1;
vis[j*z] = 1;
}
}
}
}
for (int i = 1; i <= num; i++)
{
p[i] = p[i-1];
if (!vis[i]) p[i]++;
}
printf("%d %d\n", sum, p[num]);
}
int main()
{
int n;
while (~scanf("%d", &n))
{
query(n);
}
return 0;
}