Sunday, 13 May 2012

Write a prolog program to check for armstrong number.



domains
predicates
Armstrong(integer)
Arm(integer,integer,integer)
Armst(integer,integer)
Armstr(integer,integer,integer,integer)


clauses
Armstrong(0).
Armstrong(1).
Armstrong(X):-X>0,
     R=X mod 10,
     Armst(X,R).
Armst(X,R):- R>=5,
           S=R*R*R,
     Y=X/10,
     Y =Y-1,
     Arm(Y,X,S).
Armst(X,R):- R<5,
 S=R*R*R,
 Y= X/10,
 Arm(Y,X,S).
Arm(Z,X,S):-Z>0,
   R= Z mod 10,
   Armstr(Z,X,S,R).
Arm(Z,X,S):-Z=0,
X=S.
Armstr(Z,X,S,R):-R>=5,
T=R*R*R,
Y= Z/10,
P=Y-1,
M = S+T,
Arm(P,X,M).
Armstr(Z,X,S,R):-R<5,
T=R*R*R,
Y = Z/10,
M = S + T,
Arm(Y,X,M).

5 comments

  1. This program works for 3 digit numbers only.
    For N-digit number, you must calculate (Digit)^N for all digits and sum them.
    Also refer to the A^B program.

    ReplyDelete
  2. Thanks bhaiya.....8th sem k AI lab ka chaap hatt gya..... :P :)

    ReplyDelete
  3. This logic in this blog is so faulty.

    Try this one instead.

    armstrong(integer).
    arm(integer,integer,integer).

    armstrong(0).
    armstrong(1).
    armstrong(X):- X>1,
    R is mod(X,10),
    P is R*R*R,
    T is floor(X/10),
    arm(T,X,P).

    arm(Z,X,Y):-Z=0,
    X=Y.

    arm(Z,X,Y):-Z>0,
    T is mod(Z,10),
    C is T*T*T,
    E is C + Y,
    P is floor(Z/10),
    arm(P,X,E).

    ReplyDelete
  4. Above logic is also faulty.
    Try This one instead.

    armstrong(integer,integer).
    arm(integer,integer,integer,integer).

    armstrong(0).
    armstrong(1).
    armstrong(X, K):- X>1,
    R is mod(X,10),
    P is R**K,
    T is floor(X/10),
    arm(T,X,P,K).

    arm(Z,X,Y,K):-Z=0,
    X=Y.

    arm(Z,X,Y,K):-Z>0,
    T is mod(Z,10),
    C is T**K,
    E is C + Y,
    P is floor(Z/10),
    arm(P,X,E,K).

    #test case
    # armstrong(X, number_of_digits_in_X).
    # armstrong(1634,4).

    ReplyDelete

 
© 2011-2012 ProgrammingBlue
Posts RSS Comments RSS
Back to top