0
DECLARE
n number := 12;
sum number;
BEGIN
    dbms_output.put_line(n);
    WHILE n>0 LOOP
      sum := 0;
      FOR i IN 0..n-1 LOOP
        IF n%i = 0 THEN
          sum := sum + i;
        END IF;
      END LOOP;
      dbms_output.put_line(sum);
      n := sum;
    END LOOP;
END;

I get errors such as these enter image description here

Can someone explain why , I am trying to print an Alequot Sequence

1 Answer 1

1

Two mistakes, both easily fixable.

First, sum is a PL/SQL keyword - you shouldn't use it as a variable name. You can change it to something like sum_ (with a trailing underscore), or l_sum ("l" to suggest "local variable"), etc.

Second, n%i is the modulo notation in other languages; PL/SQL uses mod(n, i).

Make these two changes and your code will work.

If you care to, you can make the code more efficient by looping from 1 to n/2 - but that's just math, it has nothing to do with "coding".

You are also doing a few other odd things. If you start with n > 0 (which you must - the Aliquot sequence only makes sense for positive integers), the updated value of n (after the inner loop) will always be greater than 0.

Worse: while some Aliquot sequences end in 1, not all do. Some end in a perfect number (for example if the input itself is a perfect number). Some sequences become periodic, with a period of 2 or more. It is also not known whether all Aliquot sequences are eventually periodic (ending in 1, in a perfect number, or a cyclical sequence of period 2 or more). So, to avoid trouble, you should put a limit to how far the computation may continue. (This is also "just math" but it does have a direct bearing on the coding too.)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.