Logo 
Search:

Artificial Intelligence Articles

Submit Article
Home » Articles » Artificial Intelligence » ProLogRSS Feeds

Prolog program to generate first 10 prime numbers and store them in a list

Posted By: Milind Mishra     Category: Artificial Intelligence     Views: 12149

Write a complete prolog program to generate first 10 prime
numbers and store them in a list. The Algorithm should be as
efficient as possible.

Code for Prolog program to generate first 10 prime numbers and store them in a list in Artificial Intelligence

trace
domains
    numlist = integer*
predicates
    start
    find_prime(integer,integer,numlist,numlist)
    prime_loop(integer,integer,numlist)
    reverselist(numlist,numlist,numlist)
goal
    clearwindow,
    start.
clauses
    start:-
        write("Enter lower limit = "),
        readint(Lower),
        write("Enter upper limit = "),
        readint(Upper),
        write("Prime List as follows:"),nl,
        prime_loop(Lower,Upper,[]).

    prime_loop(Lower,Upper,OldList):-
        Lower <= Upper,
        find_prime(Lower,2,OldList,NewList),
        LL = Lower + 1,
        prime_loop(LL,Upper,NewList).

    prime_loop(_,_,List):-
        reverselist(List,[],Outputlist),
        write(Outputlist).


    find_prime(Num,Divisor,OldList,NewList):-
        Divisor <= sqrt(Num),
        Reminder = (Num mod Divisor),
        Reminder <> 0,
        DIV = Divisor + 1,
        find_prime(Num,DIV,OldList,NewList).

    find_prime(Num,Divisor,OldList,NewList):-
        Divisor <= sqrt(Num),
        NewList = OldList.

    find_prime(Num,_,_,_):-
        Num = 0 or Num = 1.
    
    find_prime(Num,Divisor,OldList,NewList):-
        NewList = [Num | OldList].
        
    reverselist([],Inputlist,Inputlist).
    
    reverselist([Head | Tail],List1,List2):-
        reverselist(Tail,[Head | List1],List2).
        
  
Share: 



Milind Mishra
Milind Mishra author of Prolog program to generate first 10 prime numbers and store them in a list is from India.
 
View All Articles

Related Articles and Code:


 
Please enter your Comment

  • Comment should be atleast 30 Characters.
  • Please put code inside [Code] your code [/Code].

 
No Comment Found, Be the First to post comment!