5
Euclidean Least Common Divisor
F # implementation:
/// Euclidean Algorithm// Http://en.wikipedia.org/wiki/Euclidean_algorithm/// Calculate the maximum common divisor of a B/// Use the moving phase Subtraction Method/// The original ooriAlgorithmYes:/// Set C to the maximum public approx./// A = ac B = BC/// Gcd (a, B) => gcd (A-B, B) [A> B] and gcd (a-B) C, B) constantly use big minus small ones. Until a-B = 1, C is returned.
Let RECGCD a B =MatchAWith| XWhenX = 0i->B | _->Gcd (B % A)
It's easy to have the least common approx.
LetLCM a B = a * B/(gcd a B) the fifth question is to find the minimum public multiple of 1 to 20.
So long as this can be:
Let RECLcms xs =MatchXSWith| A: B: T->Lcms (lcm a B: t) | A: []->A
Lcms [1 .. 20]
========================================================== ========================================================== ======================
6
Note two formulas first: (1 + 2 + 3... + n) ^ 2 = (1 + n) * n/2) ^ 2 (1 ^ 2 + 2 ^ 2 + 3 ^ 2 +... + N ^ 2) = 1/6 * n (n + 1) (2n + 1) ========================================================== ========================================================== ====================
9
/// A Pythagorean triplet check Let Ispt a B c = A * A + B * B = C * C Let Sumeq1000 a B c = A + B + C = 1000 Let Help predicate = Let Mutable Ret = [] For AIn 1. 998 Do For B In (A + 1) .. 999 Do For C In (B + 1) .. 1000 Do If Ispt a B c & predicate a B c Then RET <-(A, B, C): Ret RET Let Findpt = help sumeq1000
// Prie solution: http://projecteuler.net/thread=9 /// Without programming: /// /// A = 2mn; B = m ^ 2-N ^ 2; C = m ^ 2 + N ^ 2; /// A + B + C = 1000; /// /// 2mn + (M ^ 2-N ^ 2) + (M ^ 2 + N ^ 2) = 1000; /// 2mn + 2 m ^ 2 = 1000; /// 2 m (m + n) = 1000; /// M (m + n) = 500; /// /// M> N; /// /// M = 20; n = 5; /// /// A = 200; B = 375; C = 425; /// Pythagorean triplet K will be: /// K {M ^ 2-N ^ 2, 2 m n, m ^ 2 + N ^ 2} /// X = A + B + C Let Ptpire x = Let Mutable Ret = [] For M In 1. X/2 Do For N In M-1 Do Let A = m * m-N * n In Let B = 2 * m * n In Let C = m * m + n * n In If A + B + C = x & A * A + B * B = C * C Then RET <-(A, B, C): Ret RET