PL/SQL Program for Prime Number

Here you will get a pl/sql program for prime number.

A number is a prime number if it is divisible by 1 or itself. For example 2, 3, 5, 7, etc are prime numbers.

While numbers like 4, 6, 8, etc are not prime.

 

PL/SQL Program for Prime Number

declare
	n number;
	i number;
	flag number;

begin
	i:=2;
	flag:=1;
	n:=&n;

	for i in 2..n/2
	loop
		if mod(n,i)=0
		then
			flag:=0;
			exit;
		end if;
	end loop;

	if flag=1
	then
		dbms_output.put_line('prime');
	else
		dbms_output.put_line('not prime');
	end if;
end;
/

 

Output

Enter value for n: 12
old 9: n:=&n;
new 9: n:=12;
not prime

16 thoughts on “PL/SQL Program for Prime Number”

    1. if half of the values of n does not give remainder 0 then the higher values preceding n/2 will also not give reminder zero and it also improves performance of the code as you are executing the condition for half of the length.
      hope u got it.

      1. Can you please explain how it worked for 2.As per my understanding i and n both are 2 so flag will be 0 hence not prime. Please correct if i am wrong

  1. hai Neeraj Mishra you are doing a grate job i like your programming .but i have one doubt in prime number program by plsql .why we take n/2 to in mod function could you please explain this.except this i have understood all you programs. please reply to me .

  2. Identifying Prime numbers from 1 to 1000
    ==========================>

    DECLARE @range int = 1000 –(Select your range from 2 to @range)
    ,@x INT = 1, @y int = 1

    While (@y <= @range)
    BEGIN
    while (@x <= @y)
    begin
    IF ((@y%@x) =0)
    BEGIN
    IF (@x = @y)
    PRINT @y
    break
    END
    IF ((@y%@x)0)
    set @x = @x+1
    end
    set @x = 2
    set @y = @y+1
    end

Leave a Comment

Your email address will not be published. Required fields are marked *