Pythagorean Theorem II

版权声明: https://blog.csdn.net/qq_40829288/article/details/80344804

In mathematics, the Pythagorean theorem — is a relation in Euclidean geometry among the three sides of a right-angled triangle. In terms of areas, it states:

In any right-angled triangle, the area of the square whose side is the hypotenuse (the side opposite the right angle) is equal to the sum of the areas of the squares whose sides are the two legs (the two sides that meet at a right angle).

The theorem can be written as an equation relating the lengths of the sides ab and c, often called the Pythagorean equation:

a2 + b2 = c2

where c represents the length of the hypotenuse, and a and b represent the lengths of the other two sides.

Given n, your task is to count how many right-angled triangles with side-lengths ab and c that satisfied an inequality 1 ≤ a ≤ b ≤ c ≤ n.

Input

The only line contains one integer n (1 ≤ n ≤ 104) as we mentioned above.

Output

Print a single integer — the answer to the problem.

Examples
Input
5
Output
1
Input
74
Output
35

解题思路:

本题大意是求在1--n能满足a^2+b^2=c^2的式子的个数;

首先想到的可能是三个for循环,但是超时,因为时间复杂度为O(n^3);所以,我们要想办法将这三个for循环变为两个for循环,这里要用到c=a^2+b^2;c是否等于(int)c这个技巧,如果等于,则证明1--n中的c满足c^2=a^2+b^2这个等式,即满足我们的条件,所以,现在只要用两个for循环循环a,b的值然后判断c=a^2+b^2;c是否等于(int)c即可;

源码:有两段代码,分别是用把c作待求量和把a(和b类似)作待求量;注意他们的区别!!

把c作待求量:

//把c作为待求量;
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
    int n,num;
    int a,b;
    double c;
    while(cin>>n)
    {
        num=0;
        for(a=1;a<=n;a++)
            for(b=1;b<=n;b++)
        {
            c=a*a+b*b;
            c=sqrt(c);
            if(c>n)
                break;
            else
            {
                if((c==(int)c)&&((int)c>=b&&b>=a))//在if判断条件内,关系运算符不能连用;
                    num++;
                else
                    continue;
            }

        }
        cout<<num<<endl;
    }
    return 0;
}

把a作待求量:

//把a作为待求量;
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
    int n;
    int b,c;
    double a;
    int num;
    while(cin>>n)
    {
        num=0;
        for(c=1;c<=n;c++)
            for(b=1;b<c;b++)
        {
            a=c*c-b*b;
            a=sqrt(a);
            if(a==(int)a&&b>=a)
                num++;
        }
        cout<<num<<endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40829288/article/details/80344804