Project Euler in PL/SQL: Problem 21

  • by

The difficulty level gets ramped up here in Project Euler’s next problem.

Problem 21:

Amicable Numbers

Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n).
If d(a) = b and d(b) = a, where a ≠ b, then a and b are an amicable pair and each of a and b are called amicable numbers.

For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220.

Evaluate the sum of all the amicable numbers under 10000.

Check this post to see the types and functions used in this solution.

DECLARE
divisors_array euler_pkg.int_array := euler_pkg.int_array();
sumz INTEGER := 0;
upper_limit INTEGER := 10000;
BEGIN
 FOR i IN 1..upper_limit LOOP
  sumz := 0;
  divisors_array := euler_pkg.get_divisors(i);
    
      for e in 1 .. divisors_array.count 
      loop
        IF divisors_array(e) != i THEN
            sumz := divisors_array(e) + sumz;
        END IF;
      end loop;
  
  INSERT INTO amicable_numbers 
  VALUES (i, sumz);
  
  COMMIT;
  END LOOP;
END;

SELECT sum(sum_divisors) 
FROM amicable_numbers a
WHERE EXISTS (SELECT 1 FROM amicable_numbers WHERE sum_divisors = a.number_in AND a.sum_divisors = number_in)
AND number_in != sum_divisors;

--output 31626

Questions or comments? Feel free to leave them below or reach out to me on Twitter!

Leave a Reply

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