Tuesday, November 23, 2021

Fun - Prime Factorization

This query will quickly find the prime factorization of a number -- Enter it on the first line and execute. This really would have been helpful in 7th grade math class!

  Example:  18 = 2 x 3 x 3

  Try some big, interesting numbers:  1234567890, 1212121212121, 9898989898989, 7171717171717

   WITH 
     step_0 as ( select /*==>*/ 1234567890 /*<==*/ as n from dual )
   , step_1 as ( select n, level i from step_0 connect by rownum <= sqrt(n) )
   , step_2 as ( select n, i, n/i as j from step_1 where mod(n,i) = 0 )
   , step_3 as ( select n, i from step_2 UNION select n, j from step_2 )
   , step_4 as ( select n, i
                      , ( select  min(i) 
                            from  step_3  x 
                           where  x.i/w.i = trunc(x.i/w.i) and  x.i > w.i
                        ) as idx 
                   from step_3  w )
   select max(n)||' = '
       || max(ltrim(rtrim(sys_connect_by_path(idx/i,'*'),'*'),'*')) as "Result"
     from step_4  
   connect by i = prior idx
   start with i = 1 ;
  

Note: this code is not the product of my brain-steam. I found this algorithm somewhere on the web and have enjoyed playing with it. I apologize for not remembering where or who originally came up with it.

No comments:

Post a Comment