Armstrong numbers [message #249275] |
Tue, 03 July 2007 21:20 |
sridhar.sangubhatla
Messages: 2 Registered: June 2007 Location: Madison
|
Junior Member |
|
|
Hello,
Can one of you clarify as to why this problem arises?
Here is the code:
DECLARE
v_number number;
v_a int;
v_b1 int;
v_b int;
v_c int;
BEGIN
FOR v_number in 1..999
LOOP
v_a := v_number/100;
v_b1 := v_number/10;
v_b := MOD(v_b1,10);
v_c := MOD(v_number,10);
if (v_a**3 + v_b**3 + v_c**3 = v_a*100 + v_b*10 + v_c*1) then
dbms_output.put_line(v_a||v_b||v_c||'is an Armstrong number');
END IF;
END LOOP;
END;
Now, this code works perfectly and gives the desired results (1,153,
370, 371, 407 being the answers).
But, when the range of the numbers is changed :
FOR v_number in 100..999
one of the results (153) is not displayed.
More surprisingly, the code works when the first number is within the
range 1 to 53, i.e.,
FOR v_number in 1..999 gives 153 as one of the results,
FOR v_number in 53..999 gives 153 as one of the results, but
FOR v_number in 54..999 doesn't give 153 as the result.
Please help.
Thnx in advance.
Sridhar
|
|
|
|
Re: Armstrong numbers [message #249278 is a reply to message #249275] |
Tue, 03 July 2007 21:44 |
rleishman
Messages: 3728 Registered: October 2005 Location: Melbourne, Australia
|
Senior Member |
|
|
153 is not an Armstrong number. The line is printing out for '53', not 153.
When v_number = 53:
- v_a = 1
- v_b = 5
- v_b1 = 5
- v_c = 3
- v_a**3 + v_b**3 + v_c**3 = 153
- v_a*100 + v_b*10 + v_c*1 = 153
Since the last two expressions are equal, a line is printed. But you don't print v_number (which would show 53), you print v_a**3 + v_b**3 + v_c**3. ie. 153
According to Wikipedia, you should actually be using
(v_a + v_b + v_3)**3.
Ross Leishman
|
|
|
|
|
|
Re: Armstrong numbers [message #250121 is a reply to message #249275] |
Sun, 08 July 2007 02:58 |
Volder
Messages: 38 Registered: April 2007 Location: Russia
|
Member |
|
|
we can get armstrong numbers without PL/SQL:
SQL> select num armstrong_numbers from
2 (select * from dual connect by level<=1000
3 model
4 partition by (rownum rn)
5 dimension by(0 dim)
6 measures(rownum-1 num, 0 n)
7 rules iterate(10) until (iteration_number+1=length(num[0]))
8 (n[0]=n[0]+power(substr(num[0],iteration_number+1,1),length(num[0]))
9 ))
10 where num=n
11 order by 1
12 /
ARMSTRONG_NUMBERS
-----------------
0
1
2
3
4
5
6
7
8
9
153
370
371
407
14 rows selected
SQL>
|
|
|
Re: Armstrong numbers [message #250164 is a reply to message #250121] |
Sun, 08 July 2007 21:49 |
rleishman
Messages: 3728 Registered: October 2005 Location: Melbourne, Australia
|
Senior Member |
|
|
An excellent example of SQL gone mad.
This is exactly what you should NOT do, because noone who comes after you will ever understand what was intended.
|
|
|
|
|
|
|
|