primary no or not in loop [message #212329] |
Thu, 04 January 2007 13:20 |
yaskumar
Messages: 5 Registered: January 2007 Location: U.S
|
Junior Member |
|
|
hello orafaq team.
i want to check the num which i insert by bind variable
is whether primary no or not?
please provide me some hints
regards
yaskumar
|
|
|
|
Re: primary no or not in loop [message #212350 is a reply to message #212329] |
Thu, 04 January 2007 20:06 |
yaskumar
Messages: 5 Registered: January 2007 Location: U.S
|
Junior Member |
|
|
hello joy.
sorry for my mistake..i need to get prime no..
your provided link not make me clear, i know
what is prime no. but i failed to solve my problem.
how could i know the accepted no is prime?
i know prime no is divisible by 1 & it's own.
please help me more.
regards
yaskumar
|
|
|
Re: primary no or not in loop [message #212367 is a reply to message #212329] |
Thu, 04 January 2007 23:18 |
pavan_034
Messages: 16 Registered: October 2006
|
Junior Member |
|
|
create the following procedure and execute it:
CREATE OR REPLACE PROCEDURE PRIME (X NUMBER) AS
Y NUMBER(4);
C NUMBER:=0;
BEGIN
FOR Y IN 2..X LOOP
IF MOD(X,Y)=0 THEN
C:=C+1;
END IF;
END LOOP;
IF C=1 THEN
DBMS_OUTPUT.PUT_LINE(X||' IS PRIME');
ELSE
DBMS_OUTPUT.PUT_LINE(X||' IS NOT A PRIME');
END IF;
END;
/
|
|
|
|
Re: primary no or not in loop [message #212391 is a reply to message #212367] |
Fri, 05 January 2007 02:12 |
JRowbottom
Messages: 5933 Registered: June 2006 Location: Sunny North Yorkshire, ho...
|
Senior Member |
|
|
You can enhance the performance of that routine by applying the following mods:
1) When checking for divisors, only check up to the next integer above the square root of the candidiate number.
2) Stop checking for divisors as soon as you find one.
Create or replace procedure prime (p_candidate in integer) as
v_prime boolean := true;
begin
for i in 2..ceil(power(p_candidate,0.5)) loop
if floor(p_candidate/i)*i = p_candidate then
v_prime := false;
exit;
end if;
end loop;
if v_prime then
dbms_output.put_line(p_candidate||' is prime.');
else
dbms_output.put_line(p_candidate||' is not prime.');
end if;
end;
If you fancy wowing the homework instructor with your mathematical skills, you could use an implementation of Wilsons theorem (p is prime IFF (p-1)! +1 is divisible by p)
declare
v_candidate pls_integer := 31;
v_prime boolean := true;
v_fact number := 1;
begin
for i in 2..v_candidate-1 loop
v_fact := v_fact * i;
end loop;
if floor((v_fact+1)/v_candidate)*v_candidate != (v_fact + 1) then
v_prime := false;
end if;
if v_prime then
dbms_output.put_line(v_candidate||' is prime.');
else
dbms_output.put_line(v_candidate||' is not prime.');
end if;
end;
|
|
|