Here is a simple PL/SQL program that you can use to check if a number is prime:
declare -- Declare a variable to hold the number num number := 5; -- Declare a variable to hold the result is_prime boolean := true; begin -- Check if the number is less than 2 if num < 2 then is_prime := false; else -- Check if the number is divisible by any number between 2 and the square root of the number for i in 2..sqrt(num) loop if mod(num, i) = 0 then is_prime := false; exit; end if; end loop; end if; -- Print the result if is_prime then dbms_output.put_line('Number is prime.'); else dbms_output.put_line('Number is not prime.'); end if; end; /
Output:
Number is prime.
Certainly! Here's a brief explanation of how the above PL/SQL program works:
- The program begins by declaring a variable
num
to hold the input number, and a variableis_prime
to hold the result of the check. - The program then checks if the number is less than 2. If it is, then it sets
is_prime
tofalse
and ends the check, since numbers less than 2 are not considered prime. - If the number is greater than or equal to 2, the program enters a loop that iterates over the numbers between 2 and the square root of the number. This is because it is not necessary to check numbers greater than the square root of the number, since they will not be divisible by the number.
- Within the loop, the program checks if the number is divisible by the current loop variable (using the
mod
function). If it is, then it setsis_prime
tofalse
and exits the loop. - If the loop completes without finding a divisor, then
is_prime
remainstrue
. The program then prints the value ofis_prime
, indicating whether the number is prime or not.
Here is another example of PL/SQL program to print prime numbers from 1 to 100.
PL/SQL program to print prime numbers from 1 to 100
declare -- Declare a variable to hold the current number num number := 1; is_prime boolean; begin -- Loop over the numbers from 1 to 100 while num <= 100 loop is_prime := true; -- Check if the number is less than 2 if num < 2 then is_prime := false; else -- Check if the number is divisible by any number between 2 and the square root of the number for i in 2..sqrt(num) loop if mod(num, i) = 0 then is_prime := false; exit; end if; end loop; end if; -- If the number is prime, print it if is_prime then dbms_output.put_line(num); end if; -- Increment the number num := num + 1; end loop; end; /
Output:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97