- 01
- 02
- 03
- 04
- 05
- 06
- 07
- 08
- 09
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
% -*- mode: Prolog -*-
:- module e9.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is cc_multi.
:- implementation.
:- import_module int, float, list, string, math.
:- func root(int) = int.
root(Number) = floor_to_int(sqrt(float(Number))).
:- func squares_under(int, int) = list(int).
squares_under(From, To) = Result:-
(Square = From * From,
(if Square =< To
then Result = [Square | squares_under(From + 1, To)]
else Result = [])).
:- pred list_to_disjunction(list(int)::in, int::out) is nondet.
list_to_disjunction([Head | Tail], Result):-
(Result = Head; list_to_disjunction(Tail, Result)).
:- pred summands_of(list(int)::in, int::in, { int, int, int }::out) is cc_nondet.
summands_of(Squares, Sum, { A, B, C }):-
list_to_disjunction(Squares, As),
list_to_disjunction(Squares, Bs),
list_to_disjunction(Squares, Cs),
As < Bs, Bs < Cs,
As + Bs = Cs,
root(As) + root(Bs) + root(Cs) = Sum,
A = As, B = Bs, C = Cs.
main(!IO):-
Sum = 1000,
Squares = squares_under(1, Sum * Sum),
(if summands_of(Squares, Sum, { A, B, C })
then io.format("Answer: A = %d, B = %d, C = %d\n", [i(A), i(B), i(C)], !IO)
else io.format("No solutions\n", [], !IO)).
Давно как-то мы не вспоминали Прожект Ойлер.
Язык: Меркури,
Эффективность решения: наверное, полный пиздец.
Для тех, кому нечем заняться: http://joyreactor.com/post/954661