Jump to content

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>(() => {
'"use strict'";
 
// Arguments: predicate, maximum perimeter
// pythTripleCount :: ((Int, Int, Int) -> Bool) -> Int -> Int
const pythTripleCount = (p, maxPerim) => {
maxPerim => {
const xs = enumFromTo(1, Math.floor(maxPerim / 2));
})); const
xs = enumFromTo(1)(
const xs = enumFromTo(1, Math.floor(maxPerim / 2));
enumFromToChar );
 
return concatMap(x => return xs.flatMap(
concatMap(yx => xs.slice(x).flatMap(
concatMap(z y => xs.slice(y).flatMap(
z => ((x + y + z <= maxPerim) &&
((x * x) + (y * y) === z * z) &&
p(x, y, z)) ? [
[x, y, z]
] : [], // (Empty lists disappear under concatenation)
xs.slice(y)), xs.slice(x )), xs
)
).length;
};
 
// GENERIC FUNCTIONS ---------------------- TEST -----------------------
const gcdmain = (x, y) => {[10, 100, 1000]
.applymap(null,n [m,=> n]);({
maxPerimeter: n,
primitivestriples: pythTripleCount((x, y, _) => gcdtrue)(x, yn) === 1, n)
primitives: pythTripleCount(
(x, y) => gcd(x)(y) === 1
) : enumFromToInt )(n)
}));
 
// concatMap :: (a -> [b]) -> [a] -> [b]
const concatMap = (f, xs) =>
xs.length > 0 ? [].concat.apply([], xs.map(f)) : [];
 
// MAIN ----------------------------------- GENERIC FUNCTIONS ----------------
// enumFromTo :: Enum a => a -> a -> [a]
const enumFromTo = (m, n) =>
(typeof m !== 'number' ? (
enumFromToChar
) : enumFromToInt)
.apply(null, [m, n]);
 
// enumFromToIntabs :: IntNum -> Int -> [Int]Num
const enumFromToIntabs = (m, n) =>
n// >=Absolute mvalue ?of Array.from({a given number
// without the length: Mathsign.floor(n - m) + 1
}, (_, i)x => m0 +> i)x :? [];(
-x
) : x;
 
// gcd :: Int -> Int -> Int
const gcd = (x, y) => {
const _gcd = (a, b) => (b === 0 ? a : _gcd(b, a % b));
return _gcd(Math.abs(x), Math.abs(y));
};
 
// enumFromTo :: Enum a => aInt -> aInt -> [aInt]
// MAIN ---------------------------------------------------
returnconst [10,enumFromTo 100,= 1000]m =>
.map(n => Array.from({
maxPerimeterlength: 1 + n, - m
}, (_, triples: pythTripleCount(xi) => true,m + ni),;
 
primitives: pythTripleCount((x, y, _) => gcd(x, y) === 1, n)
 
}));
// concatMapgcd :: (Integral a -=> [b])a -> [a] -> [b]a
const concatMapgcd = (f, xs)x =>
y => {
const zero = x.constructor(0);
const enumFromTogo = (ma, nb) =>
zero === b ? (
a
const _gcd = (a, b) => (b === 0 ? a) : _gcdgo(b, a % b));
 
return _gcdgo(Math.abs(x), Math.abs(y));
};
 
// MAIN ---
return main();
})();</lang>
{{Out}}
9,659

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.