Pythagorean triples: Difference between revisions

→‎{{header|C}}: semi-optimized code
m (wordliness)
(→‎{{header|C}}: semi-optimized code)
Line 13:
* [[List comprehensions]]
=={{header|C}}==
Sample implemention; naive method, patentlypatentedly won't scale to larger numbers, despite the attempt to optimize it. Calculating up to 10000 is already a test of patience.
<lang C>#include <stdio.h>
#include <stdlib.h>
typedef unsigned long long xint;
typedef unsigned long ulong;
 
intinline ulong gcd(intulong m, intulong n)
{
intulong t;
while (n) { t = n; n = m % n; m = t; }
return m;
}
 
int main()
{
intulong a, b, c, pytha = 0, prim = 0, max_p = 100;
intxint pythaaa, = 0bb, prim = 0cc;
for (a = 1; a < 100; a++) {
for (b = a; b < 100; b++) {
for (c = b; c < 100; c++) {
if (a + b + c > 100) break;
if (a * a + b * b != c * c) continue;
 
for (a = 1; a <= 100max_p / 3; a++) {
pytha++;
ifaa = (gcd(xint)a, b)* == 1) prim++a;
printf("a = %lu\r", a); /* show that we are working */
fflush(stdout);
 
/* max_p/2: valid limit, because one side of triangle
* must be less than the sum of the other two
*/
for (b = a + 1; b < 100max_p/2; b++) {
bb = (xint)b * b;
for (c = b + 1; c < 100max_p/2; c++) {
cc = (xint)c * c;
if (aa + bb < cc) break;
if (a + b + c > 100max_p) break;
 
if (aa + bb == cc) {
pytha++;
if (gcd(a, b) == 1) prim++;
}
}
}
}
printf("Up to 100%lu, there are %dlu triples, of which %dlu are primitive\n",
max_p, pytha, prim);
 
printf("Up to 100, there are %d triples, of which %d are primitive\n",
pytha, prim);
return 0;
}</lang>output:<lang>Up to 100, there are 17 triples, of which 7 are primitive</lang>
 
=={{header|Java}}==
[[Category:Arbitrary precision]]Theoretically, this can go "forever", but it takes a while, so only the minimum is shown. Luckily, <code>BigInteger</code> has a GCD method built in.
Anonymous user