密码算术乘法序言

时间:2014-05-16 13:54:05

标签: math prolog cryptarithmetic-puzzle

我掌握了密码算法和加法的思想,但我无法弄清楚如何进行乘法密码算术问题。它只是TWO * SIX = TWELVE或类似的东西,没有给出乘法问题的中间附加部分。我在网上找不到任何东西,我已经找到了一些问题的限制,但没有什么可以让我得到一些答案。不知道在哪里问这个,并认为这将是最好的地方。

我想知道如何解决乘法加密算术问题。

我已经得出结论:

         T  W  O
*        S  I  X
_________________
T  W  E  L  V  E


T \= 0 which also means S \= 0
T is 1-6
E is (O*X) mod 10
O or X cannot be 0 or 1 since E has to be different and 0 or 1 gives the same value 
as either O or X.

编辑:我正在使用生成和测试方法

solve(T,W,O,S,I,X,E,L,V) :-
        X = [T,W,O,S,I,X,E,L,V],
        Digits = [0,1,2,3,4,5,6,7,8,9],
        assign_digits(X, Digits),
        T > 0, 
        S > 0,
        100*T + 10*W + O * 100*S + 10*I + X =:=
        100000*T + 10000*W + 1000*E + 100*L + 10*V + E,
        write(X).

select(X, [X|R], R).
select(X, [Y|Xs], [Y|Ys]):- select(X, Xs, Ys).

assign_digits([], _List).
assign_digits([D|Ds], List):-
        select(D, List, NewList),
        assign_digits(Ds, NewList).

2 个答案:

答案 0 :(得分:6)

与约束逻辑编程有关。例如,在ECLiPSe Prolog中:

:- lib(ic).
puzzle(Vars) :-
    [T,W,O,S,I,X,E,L,V] = Vars,
    Vars :: 0..9,
    alldifferent(Vars),
    T #> 0, S #> 0,
    (100*T + 10*W + O) * (100*S + 10*I + X) #= 
      100000*T + 10000*W + 1000*E + 100*L + 10*V + E,
    labeling(Vars).

第一个解决方案:

[eclipse]: puzzle([T,W,O,S,I,X,E,L,V]).
T = 1
W = 6
O = 5
S = 9
I = 7
X = 2
E = 0
L = 3
V = 8
Yes (0.01s cpu, solution 1, maybe more) ? 

有3种不同的解决方案:

[eclipse]: puzzle([T,W,O,S,I,X,E,L,V]), writeln([T,W,O,S,I,X,E,L,V]), fail.
[1, 6, 5, 9, 7, 2, 0, 3, 8]
[2, 1, 8, 9, 6, 5, 0, 3, 7]
[3, 4, 5, 9, 8, 6, 0, 1, 7]
No (0.02s cpu)

更新 - 转换为SWI Prolog:

:- use_module(library(clpfd)).
puzzle(Vars) :-
    [T,W,O,S,I,X,E,L,V] = Vars,
    Vars ins 0..9,
    all_different(Vars),
    T #> 0, S #> 0,
    (100*T + 10*W + O) * (100*S + 10*I + X) #= 
      100000*T + 10000*W + 1000*E + 100*L + 10*V + E,
    label(Vars).

答案 1 :(得分:3)

更一般和无CLP的解决方案:

number_to_digits(Number,List) :-
        length(List,Len),
        ntb(0,Len,Number,List).

ntb(N,_,N,[]).
ntb(C,E,N,[D|L]) :-
        NE is E-1,
        V is C + D*10^NE,
        ntb(V,NE,N,L).

crypto(In1, In2, Out) :-
    term_variables([In1, In2, Out], Vars),
    permutation([0,1,2,3,4,5,6,7,8,9], Perm),
    append(_, Vars, Perm),
        number_to_digits(N1, In1),
        number_to_digits(N2, In2),
        number_to_digits(N3, Out),
        N3 is N1 * N2.

这是非常低效的,而且肯定这个问题应该像@Sergey那样使用CLP来解决,但也许有人会对没有CLP的可能解决方案感兴趣。

输入和输出:

?- crypto([T,W,O], [S,I,X], [T,W,E,L,V,E]).
T = 0,
W = 5,
O = 7,
S = 9,
I = 6,
X = 2,
E = 4,
L = 8,
V = 3;
(...)

(57 * 962 = 54834)。