Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking for prime number in boolean expression without defining a function

Tags:

oracle

plsql

Could the following PL/SQL code be completed by providing some boolean expression for IF statement?

declare
   N int := extract(year from sysdate);
begin
   if INSERT_YOUR_BOOLEAN_EXPRESSION_HERE then
      dbms_output.put_line('Current year is prime number.');
   else
      dbms_output.put_line('Current year is not prime number.');
   end if;
end;

Obviously, you can't define your own function.
Only standard Oracle 11g PL/SQL functions are allowed.
The code should work properly during years 2014-9999.


EDIT :
Answer is accepted, but problem is not solved as it was desired.
So, let's go on.

Let's reduce time interval to just 256 years in nearest future: 2014-2269
Will you be able to find another solution, more clever and more compact, without external dependencies outside Oracle server?
It requires some bright idea to succeed in this task.


EDIT #2 :
The current record is 41 symbols long: not regexp_like(rpad(1,N,1),'^(11+)\1+$')
Now may be someone can provide even more brilliant solution?
I would be impressed enough to award one more king-size bounty ))
Beat the current record by at least 1 symbol.

like image 281
Egor Skriptunoff Avatar asked Dec 26 '22 09:12

Egor Skriptunoff


2 Answers

Ok, here is another solution:

declare
N int := extract(year from sysdate);
begin
if not regexp_like(rpad('1', N, '1'),'^1?$|^(11+?)\1+$')
then
   dbms_output.put_line('Current year is prime number.');
else
   dbms_output.put_line('Current year is not prime number.');
end if;
end;

It is good up to 32767 (size of varchar2 in PL/SQL)

like image 114
vav Avatar answered Jan 13 '23 12:01

vav


Second Attempt - 40 characters

regexp_instr(rpad(2,N+1),'2(  +)\1+$')=0

Based on @vav's answer, with a few minor changes. Replacing not regexp_like... with regexp_count...=0 saves one character. The other changes are cosmetic - replacing the character 1 with 2 to distinguish between the character and the backreference; using N+1, the default rpad parameter, and spaces just to show a slightly different way to do it. regexp_count could also work here but that function is newer than other regular expression functions.

First Attempt - 54 characters

Here is a completely impracticable solution that just so happens to use a very small number of characters for the expression (54), and in no way resembles code golf.

declare
   N int := extract(year from sysdate);
begin
   if httpuritype('goo.gl/qMu5eR').getClob like'% '||n||' %' then
      dbms_output.put_line('Current year is prime number.');
   else
      dbms_output.put_line('Current year is not prime number.');
   end if;
end;
like image 45
Jon Heller Avatar answered Jan 13 '23 12:01

Jon Heller