Pythagorean triples: Difference between revisions
→JS ES6: Updated primitives, tidied.
No edit summary |
(→JS ES6: Updated primitives, tidied.) |
||
Line 2,927:
Exhaustive search of a full cartesian product. Not scalable.
<lang JavaScript>(() => {
// Arguments: predicate, maximum perimeter
// pythTripleCount :: ((Int, Int, Int) -> Bool) -> Int -> Int
const pythTripleCount =
maxPerim => {
const xs = enumFromTo(1, Math.floor(maxPerim / 2));▼
xs = enumFromTo(1)(
z => ((x + y + z <= maxPerim) &&
((x * x) + (y * y) === z * z) &&
p(x, y, z)) ? [
[x, y, z]
] : []
)
).length;
};
//
maxPerimeter: n,
primitives: pythTripleCount(
(x, y) => gcd(x)(y) === 1
}));▼
// concatMap :: (a -> [b]) -> [a] -> [b]▼
const concatMap = (f, xs) =>▼
// enumFromTo :: Enum a => a -> a -> [a]▼
const enumFromTo = (m, n) =>▼
▲ enumFromToChar
▲ ) : enumFromToInt)
▲ .apply(null, [m, n]);
//
const
// without the
-x
) : x;
▲ const gcd = (x, y) => {
const _gcd = (a, b) => (b === 0 ? a : _gcd(b, a % b));▼
return _gcd(Math.abs(x), Math.abs(y));▼
▲ };
▲ // MAIN ---------------------------------------------------
}, (_,
▲ primitives: pythTripleCount((x, y, _) => gcd(x, y) === 1, n)
▲ }));
y => {
const zero = x.constructor(0);
zero === b ? (
a
};
// MAIN ---
return main();
})();</lang>
{{Out}}
|