首页 > 解决方案 > 编写 PL/SQL 代码生成从 1 到 500 的 Armstrong 数

问题描述

我得到的输出为 a = 1。我采用了一个从 1 到 500 的 for 循环,并在外部 for 循环内使用了 while 循环。

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;

标签: oracleplsql

解决方案


这个怎么样?

  • substr拆分i为 3 个单独的数字
    • nvlnull如果这些数字不存在(还),这里是为了避免增加价值
  • power函数计算i的立方
  • 显示i是否等于r(作为“结果”)

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>

推荐阅读