原题:
Given a positive integer N, you are to write a program that computes two quantities regarding the solution of
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 <= Nsuch that p is not part of any triple (not just relatively prime triples).
The 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.
The 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
中文大意:
(来自lucky 猫)
給你一個正整數 N,你的任務是算出兩個與方程式 x2+y2=z2 的解相關的數字。( 0 < x < y < z <= N )
第一個數字是互質的數對(triples) (x,y,z) 數目。互質是指 x、y、z 沒有大於 1 的公因數。第二個數字p是在 小於等於 N 的數字內不屬於任何數對 (x,y,z) 的正整數總數,這邊 x、y、z不需要互質。
例如,N=10,可找到一組 互質數對 (3,4,5) 及 一組不互質的數對 (6,8,10), 1、2、7、9 共 4 個數字沒用到。所以N=10要輸出1與4。
Input
輸入含有多組測試資料,每組測試資料一列,有一個正整數 N (1 <= N <= 1000000)
Output
輸出一列,含兩個整數,如題目所述,數字中間以一個空白字元分隔。
Sample Input
10
25
100
500
1000000
Sample Output
1 4
4 9
16 27
80 107
159139 133926
此题貌似不能打表,数据量不允许。如果有能打表的方法,欢迎讨论
#include <bits/stdc++.h>
using namespace std;
int gcd(int a,int b)
{
if(a%b==0)
return b;
return gcd(b,a%b);
}
int ans1,ans2;
int mark[1000001];
int main()
{
ios::sync_with_stdio(false);
int t;
while(cin>>t)
{
ans2=ans1=0;
memset(mark,0,sizeof(mark));
for(int m=2;m<=sqrt(t);m++)
{
for(int n=1;n<m;n++)
{
if(m*m+n*n>t)
break;
if((n%2)+(m%2)==1&&gcd(n,m)==1)
{
ans1++;
for(int i=1;i*(m*m+n*n)<=t;i++)
{
mark[i*(m*m-n*n)]=1;
mark[i*(m*n*2)]=1;
mark[i*(m*m+n*n)]=1;
}
}
}
}
for(int i=1;i<=t;i++)
if(!mark[i])
ans2++;
cout<<ans1<<" "<<ans2<<endl;
}
return 0;
}
解答:
自己算了半天,没找出算法。由于题目很好懂,搜了一下相关公式,后来知道是毕哥达拉斯三元组,也就是勾股数。感觉自己实在是孤陋寡闻,初中高中都白上了=_=。
恶补了一下数论当中的知识,图片内容来自初等数论及其应用第5版。
所以在程序中枚举m和n即可,用书中给出的定义,如果m和n一个是奇数一个是偶数,而且m和n互质,那么m和n就可以构造一个本原勾股数。
这里第二个问,有点恶心。本来我已经把第一个问打表弄出来了,绞尽脑汁的想第二个问在数据范围内怎么打表,结果没想出来。后来看了一眼别人的代码,靠!不能打表算!