1925. Counting the number of squares and triples

topic:

Moderator:

  1. a*a + b* b = c*c is equivalent to the Pythagorean theorem

  1. a, b, c, within the range of the closed interval [1,n]

Ideas:

For three loops, make sure that loop represents c, because c>=a&&c>=b

Loop 1: inside for () ->

i starts from 1; i is less than the square value of the sum n- b ; i is incremented

Loop 2: inside for () ->

j starts at 1; j is less than the square of the sum n - a ; j is incremented

Loop three: inside for () ->

k starts from 1: k is less than n; k is incremented

answer:

class Solution {
public:
    int countTriples(int n) {
        int num = 0;
        for(int i = 1;i<=n-1;i++)
        {
            for(int j = 1;j<=n-1;j++)
            {
                for(int k = 1;k<=n;k++)
                {
                    if (i*i+j*j==k*k)
                    {
                        num++;
                    }
                }
            }
        }
        return num;
    }
};

Guess you like

Origin blog.csdn.net/Cddmic/article/details/128887776