Find Pythagorean triplet for which a + b + c = 1000

后端 未结 16 2684
离开以前
离开以前 2020-12-24 13:13

A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a2 + b2 = c2

For example, 32 + 4

16条回答
  •  长情又很酷
    2020-12-24 14:02

    From man pow:

    POW(3)                                       Linux Programmer's Manual                                      POW(3)
    
    NAME
           pow, powf, powl - power functions
    
    SYNOPSIS
           #include 
    
           double pow(double x, double y);
           float powf(float x, float y);
           long double powl(long double x, long double y);
    
           Link with -lm.
    
       Feature Test Macro Requirements for glibc (see feature_test_macros(7)):
    
           powf(), powl(): _BSD_SOURCE || _SVID_SOURCE || _XOPEN_SOURCE >= 600 || _ISOC99_SOURCE; or cc -std=c99
    
    DESCRIPTION
           The pow() function returns the value of x raised to the power of y.
    
    RETURN VALUE
           On success, these functions return the value of x to the power of y.
    
           If  x  is  a  finite  value less than 0, and y is a finite non-integer, a domain error occurs, and a NaN is
           returned.
    
           If the result overflows, a range error occurs, and the functions return HUGE_VAL, HUGE_VALF, or  HUGE_VALL,
    

    as you see, pow is using floating point arithmetic, which is unlikely to give you the exact result (although in this case should be OK, as relatively small integers have an exact representation; but don't rely on that for general cases)... use n*n to square the numbers in integer arithmetic (also, in modern CPU's with powerful floating point units the throughput can be even higher in floating point, but converting from integer to floating point has a very high cost in number of CPU cycles, so if you're dealing with integers, try to stick to integer arithmetic).

    some pseudocode to help you optimise a little bit your algorithm:

    for a from 1 to 998:
        for b from 1 to 999-a:
            c = 1000 - a - b
            if a*a + b*b == c*c:
                 print a, b, c
    

提交回复
热议问题