Check Prime numbers program in PL/SQL

In this program, you will write PL/SQL program to check whether the number entered by the user is prime or not.


declare
num number;
i number:=1;
c number:=0;
begin
num:=&num ;
for i in 1..num
loop
 if((mod(num,i))=0)
 then
   c:=c+1;
 end if;
end loop; 
if(c=2)
 then
 dbms_output.put_line(num||' is a prime');
else
 dbms_output.put_line(num||' is not a prime');
end if;
end;
/

output

Enter value for num: 13
old   6: num:=&num ;
new   6: num:=13;
13 is a prime

explanation of prime number

  • Take a number from the user and store it in a variable num.
  • Now iterate the loop from 1 to num.
  • Inside loop check, if num is divided and the remainder is zero then increment the value of c. c is counter it will count how many times num is divided perfectly with remainder zero.
  • Outside of the loop check if the value of c is two then num is a prime number because a prime number divides only two times 1 and itself. 
  • If num is divided and the remainder is not zero then num will not prime number.

Program to check prime number using while loop

This program is the same as the above program, only here w have used a while loop for checking prime numbers.


declare
num number;
i number:=1;
c number:=0;
begin
num:=&num ;
while(i <= num)
loop
 if((mod(num,i))=0)
 then
   c:=c+1;
 end if;
 i:=i+1;
end loop; 
if(c=2)
 then
 dbms_output.put_line(num||' is a prime number');
else
 dbms_output.put_line(num||' is not a prime number');
end if;
end;
/
output
Enter value for num: 31
old   6: num:=&num ;
new   6: num:=31;
31 is a prime number