107 lines
2.6 KiB
Scheme
107 lines
2.6 KiB
Scheme
#lang at-exp scheme
|
|
(require (planet soegaard/infix))
|
|
#|
|
|
Each new term in the Fibonacci sequence is generated by adding the
|
|
previous two terms. By starting with 1 and 2, the first 10 terms will be:
|
|
|
|
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
|
|
|
|
Find the sum of all the even-valued terms in the sequence which do not
|
|
exceed four million.
|
|
|#
|
|
|
|
(require (planet "while.scm" ("soegaard" "control.plt" 2 0))) ; while
|
|
(define-values (f g t) (values 1 2 0))
|
|
(define sum f)
|
|
@${
|
|
while[ g< 4000000,
|
|
when[ even?[g], sum:=sum+g];
|
|
t := f + g;
|
|
f := g;
|
|
g := t];
|
|
sum}
|
|
|
|
|
|
#|
|
|
The sum of the squares of the first ten natural numbers is,
|
|
1^2 + 2^2 + ... + 10^2 = 385
|
|
The square of the sum of the first ten natural numbers is,
|
|
(1 + 2 + ... + 10)^2 = 552 = 3025
|
|
Hence the difference between the sum of the squares of the first ten natural
|
|
numbers and the square of the sum is 3025 - 385 = 2640.
|
|
|
|
Find the difference between the sum of the squares of the first one hundred
|
|
natural numbers and the square of the sum.|#
|
|
|
|
(define n 0)
|
|
(define ns 0)
|
|
(define squares 0)
|
|
@${
|
|
sum:=0;
|
|
while[ n<100,
|
|
n := n+1;
|
|
ns := ns+n;
|
|
squares := squares + n^2];
|
|
ns^2-squares
|
|
}
|
|
|
|
|
|
|
|
#|
|
|
A Pythagorean triplet is a set of three natural numbers, a,b,c for which,
|
|
a^2 + b^2 = c^2
|
|
For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
|
|
|
|
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
|
|
Find the product abc.
|
|
|#
|
|
|
|
(let-values ([(a b c) (values 0 0 0)])
|
|
(let/cc return
|
|
(for ([k (in-range 1 100)])
|
|
(for ([m (in-range 2 1000)])
|
|
(for ([n (in-range 1 m)])
|
|
@${ a := k* 2*m*n;
|
|
b := k* (m^2 - n^2);
|
|
c := k* (m^2 + n^2);
|
|
when[ a+b+c = 1000,
|
|
display[{{k,m,n}, {a,b,c}}];
|
|
newline[];
|
|
return[a*b*c] ]})))))
|
|
|
|
|
|
#| Primality testing |#
|
|
|
|
(define (factor2 n)
|
|
; return r and s, s.t n = 2^r * s where s odd
|
|
; invariant: n = 2^r * s
|
|
(let loop ([r 0] [s n])
|
|
(let-values ([(q r) (quotient/remainder s 2)])
|
|
(if (zero? r)
|
|
(loop (+ r 1) q)
|
|
(values r s)))))
|
|
|
|
(require srfi/27) ; random-integer
|
|
|
|
(define (miller-rabin n)
|
|
; Input: n odd
|
|
(define (mod x) (modulo x n))
|
|
(define (expt x m)
|
|
(cond [(zero? m) 1]
|
|
[(even? m) @${mod[sqr[x^(m/2)] ]}]
|
|
[(odd? m) @${mod[x*x^(m-1)]}]))
|
|
(define (check? a)
|
|
(let-values ([(r s) (factor2 (sub1 n))])
|
|
; is a^s congruent to 1 or -1 modulo n ?
|
|
(and @${member[a^s,{1,mod[-1]}]} #t)))
|
|
(andmap check?
|
|
(build-list 50 (λ (_) (+ 2 (random-integer (- n 3)))))))
|
|
|
|
(define (prime? n)
|
|
(cond [(< n 2) #f]
|
|
[(= n 2) #t]
|
|
[(even? n) #f]
|
|
[else (miller-rabin n)]))
|
|
|
|
(prime? @${2^89-1})
|