Prolog program to find GCD and LCM

  • To find the GCD among two numbers:

    predicates
    go
    gcd(integer,integer)
    
    clauses
    go:-
    write("Enter the first input X1::"),
    readint(X1),
    write("Enter the second input X2::"),
    readint(X2),gcd(X1,X2).
    gcd(X1,0):-
    write(X1),nl.
    gcd(0,X2):-
    write(X2),nl.
    gcd(X1,X2):-
         X1=X2,write(X1),nl.
    gcd(X1,X2):-
         X1>X2,
         X3=X1 mod X2,gcd(X2,X3).
    gcd(X1,X2):-
         X1<X2,
        gcd(X2,X1).
    
    
  • Find the LCM of given numbers:
  • predicates
    go
    gcd(integer,integer,integer)
    
    clauses
    
    go:-
    write("enter no1="),
    readint(X),
    write("enter no2="),
    readint(Y),
    gcd(X,Y,Z),
    P=(X*Y)/Z,
    write(P).
    
    gcd(A,0,Z):-
    Z=A.
    
    gcd(0,B,Z):-
    Z=B.
    
    gcd(A,B,Z):-
    A>B,
    C=A mod B,
    gcd(B,C,Z).
    
    gcd(A,B,Z):-
    gcd(B,A,Z).
    
    This entry was posted in Prolog.

    Leave a Reply

    Please log in using one of these methods to post your comment:

    WordPress.com Logo

    You are commenting using your WordPress.com account. Log Out /  Change )

    Google photo

    You are commenting using your Google account. Log Out /  Change )

    Twitter picture

    You are commenting using your Twitter account. Log Out /  Change )

    Facebook photo

    You are commenting using your Facebook account. Log Out /  Change )

    Connecting to %s