concat([],L,L). concat([A|G],L,[A|R]):-concat(G,L,R). genere(0,[]):-!. genere(N,[N|L]):-M is N-1, genere(M,L). perm([],[]). perm([X|L],Z):-perm(L,W),insertion(X,W,Z). insertion(X,L,[X|L]). insertion(X,[Y|L],[Y|G]):-insertion(X,L,G). nombremagique(N,M):-M is (N*(N*N+1))//2. nth([H|_],1,H). nth([_|L],N,R):-N>0,P is N-1, nth(L,P,R). accumuler(_,_,_,0,0). accumuler(L,N,M,P,R):-P>0, S is P-1, nth(L,N,X), Next is N+M, accumuler(L,Next,M,S,T), R is T+X. sommeligne(L,N,I,R):- Init is N*(I-1)+1,accumuler(L, Init, 1, N, R). sommecolonne(L,N,I,R):- accumuler(L, I, N, N, R). testlignes(L,N,V):-auxlignes(L,N,V,1). auxlignes(_,N,_,K):-K=:=N+1,!. auxlignes(L,N,V,K):-sommeligne(L,N,K,V), S is K+1,auxlignes(L,N,V,S). testcolonnes(L,N,V):-auxcolonnes(L,N,V,1). auxcolonnes(_,N,_,K):-K=:=N+1,!. auxcolonnes(L,N,V,K):-sommecolonne(L,N,K,V), S is K+1,auxcolonnes(L,N,V,S). diago(L,N,R):-S is N+1, accumuler(L,1,S,N,R). adiago(L,N,R):-S is N-1, accumuler(L,N,S,N,R). carremagique(N,L1):-P is N*N, nombremagique(N,M),genere(P,L),perm(L,L1), testlignes(L1,N,M),testcolonnes(L1,N,M),diago(L1,N,M),adiago(L1,N,M).