码迷,mamicode.com
首页 > 其他好文 > 详细

POJ1305 Fermat vs. Pythagoras【毕达哥拉斯三元组】

时间:2015-03-19 22:01:29      阅读:105      评论:0      收藏:0      [点我收藏+]

标签:

题目链接:

http://poj.org/problem?id=1305


题目大意:

给一个整数N,求N范围内的本原的毕达哥拉斯三元组的个数,以及N以内毕达哥拉斯三元组不涉及

数的个数。


思路:

本原毕达哥拉斯三元组x^2 + y^2 = z^2 满足 x = m^2 - n^2,y = 2*m*n,z = m^2 + n^2,其

中m > n,且若m为奇数,则n为偶数,若m为偶数,则n为奇数。要求所给范围N内的本原毕达哥拉

三元数组,只需枚举m、n,然后将三元组x、y、z乘以i(保证i*z在所给范围内,因为z>x且z>y),

可以求出所有的毕达哥拉斯三元组。

注意:因为在n范围内,所以z < n,即m^2 + n^2 < N。


AC代码:

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<cmath>
using namespace std;
bool flag[1000010];

int GCD(int a,int b)
{
    if(b == 0)
        return a;
    return GCD(b,a%b);
}

int main()
{
    int N;
    while(cin >> N)
    {
        int temp,m,n,ans1,ans2,x,y,z;
        ans1 = ans2 = 0;
        memset(flag,false,sizeof(flag));
        temp = sqrt(N*1.0);
        for(int n = 1; n <= temp; ++n)
        {
            for(int m = n+1; m <= temp; ++m)
            {
                if(m*m + n*n > N)
                    break;
                if((n&1) != (m&1))
                {
                    if(GCD(m,n) == 1)
                    {
                        x = m*m - n*n;
                        y = 2*m*n;
                        z = m*m + n*n;
                        ans1++;
                        int i;
                        for(i = 1; ; ++i)
                        {
                            if(i*z > N)
                                break;
                            flag[i*x] = true;
                            flag[i*y] = true;
                            flag[i*z] = true;
                        }
                    }
                }
            }
        }
        for(int i = 1; i <= N; ++i)
            if(!flag[i])
                ans2++;

        cout << ans1 << ' ' << ans2 << endl;
    }

    return 0;
}


POJ1305 Fermat vs. Pythagoras【毕达哥拉斯三元组】

标签:

原文地址:http://blog.csdn.net/lianai911/article/details/44465505

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!