Home » SQL & PL/SQL » SQL & PL/SQL » PL SQL prime number program explanation. (PL SQL)
PL SQL prime number program explanation. [message #612141] Sun, 13 April 2014 03:07 Go to next message
pkchethan
Messages: 2
Registered: March 2014
Junior Member
Hi All,

I have been struck with the understanding of prime number program.

Can somebody explain me the logic of the program.

The program is as follows. Please help:

/* program to list prime numbers between 1 to 50 */

DECLARE
i number(3);
j number(3);
BEGIN
i := 2;
LOOP
j:= 2;
LOOP
exit WHEN ((mod(i, j) = 0) or (j = i));
j := j +1;
END LOOP;
IF (j = i ) THEN
dbms_output.put_line(i || ' is prime');
END IF;
i := i + 1;
exit WHEN i = 50;
END LOOP;
END;
/
Re: PL SQL prime number program explanation. [message #612143 is a reply to message #612141] Sun, 13 April 2014 05:11 Go to previous messageGo to next message
John Watson
Messages: 4523
Registered: January 2010
Location: Global Village
Senior Member
When you post code, please enclose it within [code tags as described here How to use [code] tags and make your code easier to read
The code looks reasonably self-explanatory: test the numbers to see if they have an integer divisor. If they don't, print them out.

[Updated on: Sun, 13 April 2014 05:12]

Report message to a moderator

Re: PL SQL prime number program explanation. [message #612144 is a reply to message #612141] Sun, 13 April 2014 06:28 Go to previous messageGo to next message
Michel Cadot
Messages: 58959
Registered: March 2007
Location: Nanterre, France, http://...
Senior Member
Account Moderator

What don't you understand?
The algorithm or the code text?

Re: PL SQL prime number program explanation. [message #612145 is a reply to message #612144] Sun, 13 April 2014 09:18 Go to previous message
BlackSwan
Messages: 22728
Registered: January 2009
Senior Member
It worked for me.

SQL> set serveroutput on
SQL> DECLARE 
    i NUMBER(3); 
    j NUMBER(3); 
BEGIN 
    i := 2; 

    LOOP 
        j := 2; 

        LOOP 
            EXIT WHEN ( ( MOD(i, j) = 0 ) 
                         OR ( j = i ) ); 

            j := j + 1; 
        END LOOP; 

        IF ( j = i ) THEN 
          dbms_output.Put_line(i 
                               || ' is prime'); 
        END IF; 

        i := i + 1; 

        exit WHEN i = 50; 
    END LOOP; 
END; 

/   2    3    4    5    6    7    8    9   10   11   12   13   14   15   16   17   18   19   20   21   22   23   24   25   26   27   28  
2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
23 is prime
29 is prime
31 is prime
37 is prime
41 is prime
43 is prime
47 is prime

PL/SQL procedure successfully completed.

SQL> 


Previous Topic: ORA-01830: date format picture ends before converting entire input string
Next Topic: arrange
Goto Forum:
  


Current Time: Wed Sep 03 02:41:46 CDT 2014

Total time taken to generate the page: 0.06704 seconds