题意:首先给出一种求PI近似值的方法,由Robert A. J. Matthews提出。随机给出n个无重复正整数,其中互质的数对有m对,那么比例为m/Cn,2。而这个比例接近常数6/PI^2。输入为一组数,通过上述方法估算PI。
思路:按照上述方法直接来即可。再次注意精度问题,GCC输出必须是%f,而不能用%lf。
#include <stdio.h>
#include <math.h>
int n,s[55];
int gcd(int x,int y){
int w;
while(y){
w = x%y;
x = y;
y = w;
}
return x;
}
int test(int i,int j){
return gcd(s[i],s[j]) == 1;
}
int main(){
freopen("a.txt","r",stdin);
while(scanf("%d",&n)&&n){
int i,j,num=0;
for(i = 0;i<n;i++)
scanf("%d",&s[i]);
for(i = 0;i<n-1;i++)
for(j = i+1;j<n;j++)
if(test(i,j))
num++;
if(!num)
printf("No estimate for this data set.\n");
else
printf("%.6f\n",sqrt(3.*n*(n-1)/(double)num));
}
return 0;
}