Home > Software engineering >  Write PL/SQL code to generate Armstrong number from 1 to 500
Write PL/SQL code to generate Armstrong number from 1 to 500

Time:11-12

I am getting output as a = 1. I have taken a for loop from 1 to 500 and while loops inside the outer for loop.

declare
    n number;
    s number:=0;
    r number;
    len number;
    m number;
begin
    for a in 1..500 loop
        m:=a;
        n:=a;
        len:=length(to_char(n));
        
        while(n>0) loop
            r:=mod(n,10);
            s:=s power(r,len);
            n:=trunc(n/10);
        end loop;
        
        if m=s then
            dbms_output.put_line('a='||to_char(a)');
        end if;
    end loop;
end;

CodePudding user response:

How about this?

  • substr splits i to 3 separate digits
    • nvl is here to avoid adding null value if those digits don't exist (yet)
  • power function calculates i's cube
  • display i if it is equal to r (as "result")

SQL> declare
  2    r number;
  3  begin
  4    for i in 1 .. 500 loop
  5      r :=     power(to_number(substr(to_char(i), 1, 1)), 3)  
  6           nvl(power(to_number(substr(to_char(i), 2, 1)), 3), 0)  
  7           nvl(power(to_number(substr(to_char(i), 3, 1)), 3), 0);
  8
  9      if r = i then
 10         dbms_output.put_line(i);
 11      end if;
 12    end loop;
 13  end;
 14  /
1
153
370
371
407

PL/SQL procedure successfully completed.

SQL>

CodePudding user response:

You never reset s and you do not need the final IF statement (unless you are only interested in the Armstrong numbers which equal the original number):

declare
  n number;
  s number:=0;
  r number;
  len number;
  m number;
begin
  for a in 1..500 loop
    m:=a;
    n:=a;
    s:=0;                                -- Reset s for each loop
    len:=length(to_char(n));
    while(n>0) loop
      r:=mod(n,10);
      s:=s power(r,len);
      n:=trunc(n/10);
    end loop;

    dbms_output.put_line(a || '=' || s); -- Output values for every loop.
  end loop;
end;
/

db<>fiddle here

  • Related