Munchausen numbers: Difference between revisions

(92 intermediate revisions by 34 users not shown)
Line 5:
('''Munchausen''' is also spelled: '''Münchhausen'''.)
 
For instance: &nbsp; <big> 3435 = 3<sup>3</sup> + 4<sup>4</sup> + 3<sup>3</sup> + 5<sup>5</sup> </big>
 
 
;Task
Find all Munchausen numbers between &nbsp; '''1''' &nbsp; and &nbsp; '''5000'''.
 
 
Line 14 ⟶ 15:
:* The OEIS entry: [[oeis:A046253| A046253]]
:* The Wikipedia entry: [[wp:Perfect_digit-to-digit_invariant| Perfect digit-to-digit invariant, redirected from ''Munchausen Number'']]
<br><br>
 
=={{header|11l}}==
{{trans|Python}}
<syntaxhighlight lang="11l">L(i) 5000
I i == sum(String(i).map(x -> Int(x) ^ Int(x)))
print(i)</syntaxhighlight>
 
{{out}}
<pre>
1
3435
</pre>
 
=={{header|360 Assembly}}==
<langsyntaxhighlight lang="360asm">* Munchausen numbers 16/03/2019
MUNCHAU CSECT
USING MUNCHAU,R12 base register
Line 47 ⟶ 61:
PG DC CL12' ' buffer
REGEQU
END MUNCHAU </langsyntaxhighlight>
{{out}}
<pre>
Line 53 ⟶ 67:
3435
</pre>
 
=={{header|8080 Assembly}}==
<syntaxhighlight lang="8080asm">putch: equ 2 ; CP/M syscall to print character
puts: equ 9 ; CP/M syscall to print string
org 100h
lxi b,0500h ; B C D E hold 4 digits of number
lxi d,0000h ; we work backwards from 5000
lxi h,-5000 ; HL holds negative binary representation of number
test: push h ; Keep current number
push d ; Keep last two digits (to use DE as scratch register)
push h ; Keep current number (to test against)
lxi h,0 ; Digit power sum = 0
mov a,b
call addap
mov a,c
call addap
mov a,d
call addap
mov a,e
call addap
xra a ; Correct for leading zeroes
ora b
jnz calc
dcx h
ora c
jnz calc
dcx h
ora d
jnz calc
dcx h
calc: pop d ; Load current number (as negative) into DE
dad d ; Add to sum of digits (if equal, should be 0)
mov a,h ; See if they are equal
ora l
pop d ; Restore last two digits
pop h ; Restore current number
jnz next ; If not equal, this is not a Munchhausen number
mov a,b ; Otherwise, print the number
call pdgt
mov a,c
call pdgt
mov a,d
call pdgt
mov a,e
call pdgt
call pnl
next: inx h ; Increment negative binary representation
mvi a,5
dcr e ; Decrement last digit
jp test ; If not negative, try next number
mov e,a ; Otherwise, set to 5,
inx h ; Add 4 extra to HL,
inx h
inx h
inx h
dcr d
jp test
mov d,a
push d ; Add 40 extra to HL,
lxi d,40
dad d
pop d
dcr c
jp test
mov c,a
push d ; Add 400 extra to HL,
lxi d,400
dad d
pop d
dcr b
jp test
ret ; When B<0, we're done
;;; Print A as digit
pdgt: adi '0'
push b ; Save all registers (CP/M tramples them)
push d
push h
mov e,a ; Print character
mvi c,putch
call 5
restor: pop h ; Restore registers
pop d
pop b
ret
;;; Print newline
pnl: push b ; Save all registers
push d
push h
lxi d,nl ; Print newline
mvi c,puts
call 5
jmp restor ; Restore registers
nl: db 13,10,'$'
;;; Add A^A to HL
addap: push d ; Keep DE
push h ; Keep HL
add a ; A *= 2 (entries are 2 bytes wide)
mvi d,0 ; DE = lookup table index
mov e,a
lxi h,dpow ; Calculate table address
dad d
mov e,m ; Load low byte into E
inx h
mov d,m ; Load high byte into D
pop h ; Retrieve old HL
dad d ; Add power
pop d ; Restore DE
ret
dpow: dw 1,1,4,27,256,3125 ; 0^0 to 5^5 lookup table</syntaxhighlight>
 
{{out}}
 
<pre>3435
0001</pre>
 
=={{header|ABC}}==
<syntaxhighlight lang="ABC">HOW TO REPORT munchausen n:
PUT 0 IN sum
PUT n IN m
WHILE m > 0:
PUT m mod 10 IN digit
PUT sum + digit**digit IN sum
PUT floor(m/10) IN m
REPORT sum = n
 
FOR n IN {1..5000}:
IF munchausen n: WRITE n/</syntaxhighlight>
{{out}}
<pre>1
3435</pre>
 
=={{header|Action!}}==
<syntaxhighlight lang="action!">;there are considered digits 0-5 because 6^6>5000
DEFINE MAXDIGIT="5"
INT ARRAY powers(MAXDIGIT+1)
 
INT FUNC Power(BYTE x)
INT res
BYTE i
 
IF x=0 THEN RETURN (0) FI
res=1
FOR i=0 TO x-1
DO
res==*x
OD
RETURN (res)
 
BYTE FUNC IsMunchausen(INT x)
INT sum,tmp
BYTE d
 
tmp=x sum=0
WHILE tmp#0
DO
d=tmp MOD 10
IF d>MAXDIGIT THEN
RETURN (0)
FI
sum==+powers(d)
tmp==/10
OD
IF sum=x THEN
RETURN (1)
FI
RETURN (0)
 
PROC Main()
INT i
 
FOR i=0 TO MAXDIGIT
DO
powers(i)=Power(i)
OD
FOR i=1 TO 5000
DO
IF IsMunchausen(i) THEN
PrintIE(i)
FI
OD
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Munchausen_numbers.png Screenshot from Atari 8-bit computer]
<pre>
1
3435
</pre>
 
=={{header|Ada}}==
<syntaxhighlight lang="ada">with Ada.Text_IO;
 
procedure Munchausen is
 
function Is_Munchausen (M : in Natural) return Boolean is
Table : constant array (Character range '0' .. '9') of Natural :=
(0**0, 1**1, 2**2, 3**3, 4**4,
5**5, 6**6, 7**7, 8**8, 9**9);
Image : constant String := M'Image;
Sum : Natural := 0;
begin
for I in Image'First + 1 .. Image'Last loop
Sum := Sum + Table (Image (I));
end loop;
return Image = Sum'Image;
end Is_Munchausen;
 
begin
for M in 1 .. 5_000 loop
if Is_Munchausen (M) then
Ada.Text_IO.Put (M'Image);
end if;
end loop;
Ada.Text_IO.New_Line;
end Munchausen;</syntaxhighlight>
 
{{out}}
<pre> 1 3435</pre>
 
=={{header|ALGOL 68}}==
<langsyntaxhighlight lang="algol68"># Find Munchausen Numbers between 1 and 5000 #
# note that 6^6 is 46 656 so we only need to consider numbers consisting of 0 to 5 #
Line 93 ⟶ 324:
FI
OD
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 101 ⟶ 332:
 
Alternative that finds all 4 Munchausen numbers. As noted by the Pascal sample, we only need to consider one arrangement of the digits of each number (e.g. we only need to consider 3345, not 3435, 3453, etc.). This also relies on the non-standard 0^0 = 0.
<langsyntaxhighlight lang="algol68"># Find all Munchausen numbers - note 11*(9^9) has only 10 digits so there are no #
# Munchausen numbers with 11+ digits #
# table of Nth powers - note 0^0 is 0 for Munchausen numbers, not 1 #
Line 159 ⟶ 390:
OD
OD
OD</langsyntaxhighlight>
{{out}}
<pre>
Line 170 ⟶ 401:
=={{header|ALGOL W}}==
{{Trans|ALGOL 68}}
<langsyntaxhighlight lang="algolw">% Find Munchausen Numbers between 1 and 5000 %
% note that 6^6 is 46 656 so we only need to consider numbers consisting of 0 to 5 %
begin
Line 212 ⟶ 443:
end
 
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 219 ⟶ 450:
</pre>
 
=={{header|AppleScriptAPL}}==
{{works with|Dyalog APL}}
 
<syntaxhighlight lang="apl">(⊢(/⍨)⊢=+/∘(*⍨∘⍎¨⍕)¨)⍳ 5000</syntaxhighlight>
<lang AppleScript>-- MUNCHAUSEN NUMBER ? -------------------------------------------------------
 
{{out}}
 
<pre>1 3435</pre>
 
=={{header|AppleScript}}==
===Functional===
<syntaxhighlight lang="applescript">------------------- MUNCHAUSEN NUMBER ? --------------------
 
-- isMunchausen :: Int -> Bool
Line 235 ⟶ 475:
(class of n is integer) and ¬
n = foldl(digitPowerSum, 0, characters of (n as string)) = n
end isMunchausen
 
 
-- TEST ------------------------------------------- TEST ---------------------------
on run
Line 250 ⟶ 490:
 
 
-- GENERIC FUNCTIONS ------------------------------------ GENERIC FUNCTIONS ---------------------
 
-- enumFromTo :: Int -> Int -> [Int]
on enumFromTo(m, n)
if m > n then
set dlst to -1{}
repeat with i from m to n
set end of lst to i
end repeat
lst
else
set d to 1{}
end if
set lst to {}
repeat with i from m to n by d
set end of lst to i
end repeat
return lst
end enumFromTo
 
-- filter :: (a -> Bool) -> [a] -> [a]
on filter(fp, xs)
tell mReturn(fp)
set lst to {}
set lng to length of xs
Line 301 ⟶ 540:
end script
end if
end mReturn</langsyntaxhighlight>
{{Out}}
<syntaxhighlight lang AppleScript="applescript">{1, 3435}</langsyntaxhighlight>
 
===Iterative===
 
More straightforwardly:
 
<syntaxhighlight lang="applescript">set MunchhausenNumbers to {}
repeat with i from 1 to 5000
if (i > 0) then
set n to i
set s to 0
repeat until (n is 0)
tell n mod 10 to set s to s + it ^ it
set n to n div 10
end repeat
if (s = i) then set end of MunchhausenNumbers to i
end if
end repeat
 
return MunchhausenNumbers</syntaxhighlight>
{{Out}}
<syntaxhighlight lang="applescript">{1, 3435}</syntaxhighlight>
 
=={{header|Arturo}}==
<syntaxhighlight lang="rebol">munchausen?: function [n][
n = sum map split to :string n 'digit [
d: to :integer digit
d^d
]
]
 
loop 1..5000 'x [
if munchausen? x ->
print x
]</syntaxhighlight>
 
{{out}}
 
<pre>1
3435</pre>
 
=={{header|AutoHotkey}}==
<syntaxhighlight lang="autohotkey">Loop, 5000
{
Loop, Parse, A_Index
var += A_LoopField**A_LoopField
if (var = A_Index)
num .= var "`n"
var := 0
}
Msgbox, %num%</syntaxhighlight>
{{out}}
<pre>
1
3435
</pre>
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f MUNCHAUSEN_NUMBERS.AWK
BEGIN {
Line 321 ⟶ 615:
exit(0)
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 330 ⟶ 624:
=={{header|BASIC}}==
This should need only minimal modification to work with any old-style BASIC that supports user-defined functions. The call to <code>INT</code> in line 10 is needed because the exponentiation operator may return a (floating-point) value that is slightly too large.
<langsyntaxhighlight lang="basic">10 DEF FN P(X)=INT(X^X*SGN(X))
20 FOR I=0 TO 5
30 FOR J=0 TO 5
Line 341 ⟶ 635:
100 NEXT K
110 NEXT J
120 NEXT I</langsyntaxhighlight>
{{out}}
<pre> 1
Line 348 ⟶ 642:
==={{header|Sinclair ZX81 BASIC}}===
Works with 1k of RAM. The word <code>FAST</code> in line 10 shouldn't be taken <i>too</i> literally. We don't have <code>DEF FN</code>, so the expression for exponentiation-where-zero-to-the-power-zero-equals-zero is written out inline.
<langsyntaxhighlight lang="basic"> 10 FAST
20 FOR I=0 TO 5
30 FOR J=0 TO 5
Line 360 ⟶ 654:
110 NEXT J
120 NEXT I
130 SLOW</langsyntaxhighlight>
{{out}}
<pre>1
Line 366 ⟶ 660:
 
=={{header|BBC BASIC}}==
<langsyntaxhighlight lang="bbcbasic">REM >munchausen
FOR i% = 0 TO 5
FOR j% = 0 TO 5
Line 384 ⟶ 678:
= 0
ELSE
= x% ^ x%</langsyntaxhighlight>
{{out}}
<pre> 1
3435</pre>
 
=={{header|BQN}}==
<syntaxhighlight lang="bqn">Dgts ← •Fmt-'0'˙
IsMnch ← ⊢=+´∘(⋆˜ Dgts)
IsMnch¨⊸/ 1+↕5000</syntaxhighlight>
{{out}}
<pre>⟨ 1 3435 ⟩</pre>
 
=={{header|C}}==
Adapted from Zack Denton's code posted on [https://zach.se/munchausen-numbers-and-how-to-find-them/ Munchausen Numbers and How to Find Them].
<langsyntaxhighlight Clang="c">#include <stdio.h>
#include <math.h>
 
Line 413 ⟶ 714:
}
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>1
Line 419 ⟶ 720:
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">Func<char, int> toInt = c => c-'0';
 
foreach (var i in Enumerable.Range(1,5000)
.Where(n => n == n.ToString()
.Sum(x => Math.Pow(toInt(x), toInt(x)))))
Console.WriteLine(i);</langsyntaxhighlight>
{{out}}
<pre>1
Line 431 ⟶ 732:
=== Faster version ===
{{Trans|Kotlin}}
<langsyntaxhighlight lang="csharp">using System;
 
namespace Munchhausen
Line 473 ⟶ 774:
}
}
}</langsyntaxhighlight>
<pre>0
1
Line 481 ⟶ 782:
{{trans|Visual Basic .NET}}
Search covers all 11 digit numbers (as pointed out elsewhere, 11*(9^9) has only 10 digits, so there are no Munchausen numbers with 11+ digits), not just the first half of the 9 digit numbers. Computation time is under 1.5 seconds.
<langsyntaxhighlight lang="csharp">using System;
 
static class Program
Line 506 ⟶ 807:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>0
Line 514 ⟶ 815:
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">
#include <math.h>
#include <iostream>
Line 537 ⟶ 838:
return 0;
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 547 ⟶ 848:
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="lisp">(ns async-example.core
(:require [clojure.math.numeric-tower :as math])
(:use [criterium.core])
Line 570 ⟶ 871:
 
(println (find-numbers 5000))
</syntaxhighlight>
</lang>
{{Output}}
<pre>
Line 576 ⟶ 877:
</pre>
 
=={{header|CLU}}==
<syntaxhighlight lang="clu">digits = iter (n: int) yields (int)
while n>0 do
yield(n//10)
n := n/10
end
end digits
 
munchausen = proc (n: int) returns (bool)
k: int := 0
for d: int in digits(n) do
% Note: 0^0 is to be regarded as 0
if d~=0 then k := k + d ** d end
end
return(n = k)
end munchausen
 
start_up = proc ()
po: stream := stream$primary_output()
for i: int in int$from_to(1,5000) do
if munchausen(i) then stream$putl(po, int$unparse(i)) end
end
end start_up</syntaxhighlight>
{{out}}
<pre>1
3435</pre>
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">
;;; check4munch maximum &optional b
;;; Return a list with all Munchausen numbers less then or equal to maximum.
Line 613 ⟶ 940:
(let ((dm (divmod n base)))
(n2base (car dm) base (cons (cadr dm) digits)))))
</syntaxhighlight>
</lang>
 
{{Out}}
Line 622 ⟶ 949:
T
</pre>
 
=={{header|COBOL}}==
<syntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
PROGRAM-ID. MUNCHAUSEN.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 VARIABLES.
03 CANDIDATE PIC 9(4).
03 DIGITS PIC 9 OCCURS 4 TIMES, REDEFINES CANDIDATE.
03 DIGIT PIC 9.
03 POWER-SUM PIC 9(5).
 
01 OUTPUT-LINE.
03 OUT-NUM PIC ZZZ9.
 
PROCEDURE DIVISION.
BEGIN.
PERFORM MUNCHAUSEN-TEST VARYING CANDIDATE FROM 1 BY 1
UNTIL CANDIDATE IS GREATER THAN 6000.
STOP RUN.
 
MUNCHAUSEN-TEST.
MOVE ZERO TO POWER-SUM.
MOVE 1 TO DIGIT.
INSPECT CANDIDATE TALLYING DIGIT FOR LEADING '0'.
PERFORM ADD-DIGIT-POWER VARYING DIGIT FROM DIGIT BY 1
UNTIL DIGIT IS GREATER THAN 4.
IF POWER-SUM IS EQUAL TO CANDIDATE,
MOVE CANDIDATE TO OUT-NUM,
DISPLAY OUTPUT-LINE.
ADD-DIGIT-POWER.
COMPUTE POWER-SUM =
POWER-SUM + DIGITS(DIGIT) ** DIGITS(DIGIT)</syntaxhighlight>
{{out}}
<pre> 1
3435</pre>
 
=={{header|Cowgol}}==
<syntaxhighlight lang="cowgol">include "cowgol.coh";
 
sub digitPowerSum(n: uint16): (sum: uint32) is
var powers: uint32[10] :=
{1, 1, 4, 27, 256, 3125, 46656, 823543, 16777216, 387420489};
sum := 0;
loop
sum := sum + powers[(n % 10) as uint8];
n := n / 10;
if n == 0 then break; end if;
end loop;
end sub;
 
var n: uint16 := 1;
while n < 5000 loop
if n as uint32 == digitPowerSum(n) then
print_i16(n);
print_nl();
end if;
n := n + 1;
end loop;</syntaxhighlight>
 
{{out}}
 
<pre>1
3435</pre>
 
=={{header|Craft Basic}}==
<syntaxhighlight lang="basic">for i = 0 to 5
 
for j = 0 to 5
 
for k = 0 to 5
 
for l = 0 to 5
 
let m = int(i ^ i * sgn(i))
let m = m + int(j ^ j * sgn(j))
let m = m + int(k ^ k * sgn(k))
let m = m + int(l ^ l * sgn(l))
 
let n = 1000 * i + 100 * j + 10 * k + l
 
if m = n and m > 0 then
 
print m
 
endif
 
wait
 
next l
 
next k
 
next j
 
next i</syntaxhighlight>
{{out| Output}}<pre>1
3435</pre>
 
=={{header|D}}==
{{trans|C}}
<langsyntaxhighlight Dlang="d">import std.stdio;
 
void main() {
Line 645 ⟶ 1,073:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>1
Line 653 ⟶ 1,081:
Needs a modern Dc due to <code>~</code>.
Use <code>S1S2l2l1/L2L1%</code> instead of <code>~</code> to run it in older Dcs.
<langsyntaxhighlight lang="dc">[ O ~ S! d 0!=M L! d ^ + ] sM
[p] sp
[z d d lM x =p z 5001>L ] sL
lL x</langsyntaxhighlight>
Cosmetic: The stack is dirty after execution. The loop <code>L</code> needs a fix if that is a problem.
 
=={{header|Delphi}}==
See [https://rosettacode.org/wiki/Munchausen_numbers#Pascal Pascal].
 
=={{header|Draco}}==
<syntaxhighlight lang="draco">proc munchausen(word n) bool:
/* d^d for d>6 does not fit in a 16-bit word,
* it follows that any 16-bit integer containing
* a digit d>6 is not a Munchausen number */
[7]word dpow = (1, 1, 4, 27, 256, 3125, 46656);
word m, d, sum;
 
m := n;
sum := 0;
while
d := m % 10;
m>0 and d<=6
do
m := m/10;
sum := sum + dpow[d]
od;
d<=6 and sum=n
corp;
 
proc main() void:
word n;
for n from 1 upto 5000 do
if munchausen(n) then
writeln(n)
fi
od
corp</syntaxhighlight>
{{out}}
<pre>1
3435</pre>
 
=={{header|EasyLang}}==
<syntaxhighlight>
for i = 1 to 5000
sum = 0
n = i
while n > 0
dig = n mod 10
sum += pow dig dig
n = n div 10
.
if sum = i
print i
.
.
</syntaxhighlight>
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule Munchausen do
@pow for i <- 0..9, into: %{}, do: {i, :math.pow(i,i) |> round}
Line 670 ⟶ 1,149:
Enum.each(1..5000, fn i ->
if Munchausen.number?(i), do: IO.puts i
end)</langsyntaxhighlight>
 
{{out}}
Line 677 ⟶ 1,156:
3435
</pre>
 
=={{header|F sharp|F#}}==
<syntaxhighlight lang="fsharp">let toFloat x = x |> int |> fun n -> n - 48 |> float
let power x = toFloat x ** toFloat x |> int
let isMunchausen n = n = (string n |> Seq.map char |> Seq.map power |> Seq.sum)
 
printfn "%A" ([1..5000] |> List.filter isMunchausen)</syntaxhighlight>
{{out}}
<pre>[1; 3435]</pre>
 
=={{header|Factor}}==
<syntaxhighlight lang="factor">USING: kernel math.functions math.ranges math.text.utils
<lang factor>
USING: kernel math.functions math.ranges math.text.utils
prettyprint sequences ;
IN: rosetta-code.munchausen
 
: munchausen? ( n -- ? )
dup 1 digit-groups dup [ ^ ] 2map sum = ;
 
: main ( -- ) 5000 [1,b] [ munchausen? ] filter . ;</syntaxhighlight>
 
MAIN: main
</lang>
{{out}}
<pre>
Line 696 ⟶ 1,179:
</pre>
 
=={{header|FōrmulæFALSE}}==
<syntaxhighlight lang="false">0[1+$5000>~][
$$0\[$][
$10/$@\10*-
$0>[
$$[1-$][\2O*\]#
%\%
]?
@+\
]#
%=[$.10,]?
]#%</syntaxhighlight>
 
{{out}}
In [http://wiki.formulae.org/Munchausen_numbers this] page you can see the solution of this task.
 
<pre>1
Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text ([http://wiki.formulae.org/Editing_F%C5%8Drmul%C3%A6_expressions more info]). Moreover, there can be multiple visual representations of the same program. Even though it is possible to have textual representation &mdash;i.e. XML, JSON&mdash; they are intended for transportation effects more than visualization and edition.
3435</pre>
 
=={{header|FOCAL}}==
The option to show Fōrmulæ programs and their results is showing images. Unfortunately images cannot be uploaded in Rosetta Code.
<syntaxhighlight lang="focal">01.10 F N=1,5000;D 2
 
02.10 S M=N;S S=0
02.20 S D=M-FITR(M/10)*10
02.25 S S=S+D^D
02.30 S M=FITR(M/10)
02.40 I (M),2.5,2.2
02.50 I (N-S)2.7,2.6,2.7
02.60 T %4,N,!
02.70 R</syntaxhighlight>
 
{{out}}
 
<pre>= 1
= 3435</pre>
 
=={{header|Forth}}==
{{works with|GNU Forth|0.7.0}}
<syntaxhighlight lang="forth">
: dig.num \ returns input number and the number of its digits ( n -- n n1 )
dup
0 swap
begin
swap 1 + swap
dup 10 >= while
10 /
repeat
drop ;
: to.self \ returns input number raised to the power of itself ( n -- n^n )
dup 1 = if drop 1 else \ positive numbers only, zero and negative returns zero
dup 0 <= if drop 0 else
dup
1 do
dup
loop
dup
1 do
*
loop
then then ;
 
: ten.to \ ( n -- 10^n ) returns 1 for zero and negative
dup 0 <= if drop 1 else
dup 1 = if drop 10 else
10 swap
1 do
10 *
loop then then ;
: zero.divmod \ /mod that returns zero if number is zero
dup
0 = if drop 0
else /mod
then ;
: split.div \ returns input number and its digits ( n -- n n1 n2 n3....)
dup 10 < if dup 0 else \ duplicates single digit numbers adds 0 for add.pow
dig.num \ provides number of digits
swap dup rot dup 1 - ten.to swap \ stack juggling, ten raised to number of digits - 1...
1 do \ ... is the needed divisor, counter on top and ...
dup rot swap zero.divmod swap rot 10 / \ ...division loop
loop drop then ;
: add.pow \ raises each number on the stack except last one to ...
to.self \ ...the power of itself and adds them
depth \ needs at least 3 numbers on the stack
2 do
swap to.self +
loop ;
 
: check.num
split.div add.pow ;
: munch.num \ ( n -- ) displays Munchausen numbers between 1 and n
1 +
page
1 do
i check.num = if i . cr
then loop ;
</syntaxhighlight>
{{out}}
<pre>
1
3435
ok
</pre>
 
=={{header|Fortran}}==
{{trans|360 Assembly}}
===Fortran IV===
<langsyntaxhighlight lang="fortran">C MUNCHAUSEN NUMBERS - FORTRAN IV
DO 2 I=1,5000
IS=0
Line 718 ⟶ 1,300:
1 II=IR
2 IF(IS.EQ.I) WRITE(*,*) I
END </langsyntaxhighlight>
{{out}}
<pre>
Line 725 ⟶ 1,307:
</pre>
===Fortran 77===
<langsyntaxhighlight lang="fortran">! MUNCHAUSEN NUMBERS - FORTRAN 77
DO I=1,5000
IS=0
Line 738 ⟶ 1,320:
IF(IS.EQ.I) WRITE(*,*) I
END DO
END </langsyntaxhighlight>
{{out}}
<pre>
Line 744 ⟶ 1,326:
3435
</pre>
 
 
=={{header|FreeBASIC}}==
===Version 1===
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
' Cache n ^ n for the digits 1 to 9
' Note than 0 ^ 0 specially treated as 0 (not 1) for this purpose
Line 779 ⟶ 1,360:
Print "Press any key to quit"
 
Sleep</langsyntaxhighlight>
{{out}}
<pre>The Munchausen numbers between 0 and 500000000 are :
Line 787 ⟶ 1,368:
438579088</pre>
===Version 2===
<langsyntaxhighlight lang="freebasic">' version 12-10-2017
' compile with: fbc -s console
 
Line 851 ⟶ 1,432:
Print : Print "hit any key to end program"
Sleep
End</langsyntaxhighlight>
{{out}}
<pre>0
Line 858 ⟶ 1,439:
438579088</pre>
 
=={{header|F sharp|F#Frink}}==
<syntaxhighlight lang="frink">isMunchausen = { |x|
<lang fsharp>let toFloat x = x |> int |> fun n -> n - 48 |> float
sum = 0
let power x = toFloat x ** toFloat x |> int
for d = integerDigits[x]
let isMunchausen n = n = (string n |> Seq.map char |> Seq.map power |> Seq.sum)
sum = sum + d^d
return sum == x
}
 
printfn "%A" (println[select[1..5000] |>to List.filter5000, isMunchausen)]]</langsyntaxhighlight>
{{out}}
<pre>[1; 3435]</pre>
[1, 3435]
</pre>
 
=={{header|Fōrmulæ}}==
 
{{FormulaeEntry|page=https://formulae.org/?script=examples/Munchausen_numbers}}
 
'''Solution'''
 
[[File:Fōrmulæ - Munchausen numbers 01.png]]
 
'''Test case 1''' Find all Munchausen numbers between 1 and 5000
 
[[File:Fōrmulæ - Munchausen numbers 02.png]]
 
[[File:Fōrmulæ - Munchausen numbers 03.png]]
 
'''Test case 2''' Show the Munchausen numbers between 1 and 5,000 from bases 2 to 10
 
[[File:Fōrmulæ - Munchausen numbers 04.png]]
 
[[File:Fōrmulæ - Munchausen numbers 05.png]]
 
=={{header|Go}}==
{{trans|Kotlin}}
<langsyntaxhighlight lang="go">package main
 
import(
Line 904 ⟶ 1,510:
}
fmt.Println()
}</langsyntaxhighlight>
 
{{out}}
Line 912 ⟶ 1,518:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import DataControl.ListMonad (unfoldrjoin)
import Data.List (unfoldr)
 
isMunchausen :: Integer -> Bool
isMunchausen =
isMunchausen n = (n ==) $ sum $ map (\x -> x^x) $ unfoldr digit n where
(==)
digit 0 = Nothing
digit n = Just<*> (r,q)sum where. map (q,rjoin (^)) =. nunfoldr `divMod` 10digit)
 
digit 0 = Nothing
digit n = Just (r, q) where (q, r) = n `divMod` 10
 
main :: IO ()
main = print $ filter isMunchausen [1 .. 5000]</langsyntaxhighlight>
{{out}}
<pre>[1,3435]</pre>
 
The Haskell libraries provide a lot of flexibility – we could also reworkreduce the sum, map, and unfoldmap (above) down to a single foldfoldr:
 
<langsyntaxhighlight lang="haskell">import ControlData.MonadChar (joindigitToInt)
import Data.Char (digitToInt)
 
isMunchausen :: Int -> Bool
isMunchausen =
(==)
let go = (+) . join (^) . digitToInt
in (==) <*> foldr go((+) . (id >>=) (^) . digitToInt) 0 . show
 
main :: IO ()
main = print $ filter isMunchausen [1 .. 5000]</langsyntaxhighlight>
 
Or, without digitToInt, but importing join, swap and bool.
<syntaxhighlight lang="haskell">import Control.Monad (join)
import Data.Bool (bool)
import Data.List (unfoldr)
import Data.Tuple (swap)
 
isMunchausen :: Integer -> Bool
isMunchausen =
(==)
<*> ( foldr ((+) . join (^)) 0
. unfoldr
( ( flip bool Nothing
. Just
. swap
. flip quotRem 10
)
<*> (0 ==)
)
)
 
main :: IO ()
main = print $ filter isMunchausen [1 .. 5000]</syntaxhighlight>
 
{{Out}}
<pre>[1,3435]</pre>
 
=={{header|J}}==
 
Here, it would be useful to have a function which sums the powers of the digits of a number. Once we have that we can use it with an equality test to filter those integers:
 
<langsyntaxhighlight Jlang="j"> munch=: +/@(^~@(10&#.inv))
(#~ ] = munch"0) 1+i.5000
1 3435</langsyntaxhighlight>
 
Note that [[wp:Munchausen_number|wikipedia]] claims that 0=0^0 in the context of Munchausen numbers. It's not clear why this should be (1 is the multiplicative identity and if you do not multiply it by zero it should still be 1), but it's easy enough to implement. Note also that this does not change the result for this task:
 
<langsyntaxhighlight Jlang="j"> munch=: +/@((**^~)@(10&#.inv))
(#~ ] = munch"0) 1+i.5000
1 3435</langsyntaxhighlight>
 
=={{header|Java}}==
Adapted from Zack Denton's code posted on [https://zach.se/munchausen-numbers-and-how-to-find-them/ Munchausen Numbers and How to Find Them].
<syntaxhighlight lang="java">
<lang Java>
public class Main {
public static void main(String[] args) {
Line 967 ⟶ 1,599:
}
 
</syntaxhighlight>
</lang>
{{out}}
<pre>1 (munchausen)
Line 974 ⟶ 1,606:
=== Faster version ===
{{trans|Kotlin}}
<langsyntaxhighlight lang="java">public class Munchhausen {
 
static final long[] cache = new long[10];
Line 1,002 ⟶ 1,634:
return sum == n;
}
}</langsyntaxhighlight>
<pre>0
1
Line 1,009 ⟶ 1,641:
 
=={{header|JavaScript}}==
 
===ES6===
 
<langsyntaxhighlight lang="javascript">for (let i of [...Array(5000).keys()]
.filter(n => n == n.toString().split('')
.reduce((a, b) => a+Math.pow(parseInt(b),parseInt(b)), 0)))
console.log(i);</langsyntaxhighlight>
{{out}}
<pre>1
Line 1,023 ⟶ 1,654:
Or, composing reusable primitives:
 
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
'use strict';
 
Line 1,054 ⟶ 1,685:
// MAIN ---
return main();
})();</langsyntaxhighlight>
{{Out}}
<syntaxhighlight lang JavaScript="javascript">[1, 3435]</langsyntaxhighlight>
 
=={{header|jq}}==
{{works with|jq|1.5}}
<langsyntaxhighlight lang="jq">def sigma( stream ): reduce stream as $x (0; . + $x ) ;
 
def ismunchausen:
Line 1,067 ⟶ 1,698:
 
# Munchausen numbers from 1 to 5000 inclusive:
range(1;5001) | select(ismunchausen)</langsyntaxhighlight>
{{out}}
<langsyntaxhighlight lang="jq">1
3435</langsyntaxhighlight>
 
=={{header|Julia}}==
{{works with|Julia|1.0}}
<langsyntaxhighlight lang="julia">println([n for n = 1:5000 if sum(d^d for d in digits(n)) == n])</langsyntaxhighlight>
 
{{out}}
Line 1,081 ⟶ 1,712:
=={{header|Kotlin}}==
As it doesn't take long to find all 4 known Munchausen numbers, we will test numbers up to 500 million here rather than just 5000:
<langsyntaxhighlight lang="scala">// version 1.0.6
 
val powers = IntArray(10)
Line 1,105 ⟶ 1,736:
for (i in 0..500000000) if (isMunchausen(i))print ("$i ")
println()
}</langsyntaxhighlight>
 
{{out}}
Line 1,113 ⟶ 1,744:
</pre>
 
=={{header|LangurLambdatalk}}==
<syntaxhighlight lang="scheme">
{def munch
{lambda {:w}
{= :w {+ {S.map {{lambda {:w :i}
{pow {W.get :i :w} {W.get :i :w}}} :w}
{S.serie 0 {- {W.length :w} 1}}}}} }}
-> munch
 
{S.map {lambda {:i} {if {munch :i} then :i else}}
{S.serie 1 5000}}
->
1
3435
</syntaxhighlight>
 
=={{header|langur}}==
{{trans|C#}}
<langsyntaxhighlight Langurlang="langur"># sum power of digits
val .spod = f(fn .n): fold f .x fn{+ .y}, map(ffn (.x-'0'): .x^ (.x-'0'), stringToCps2n toStringstring .n)
 
# Munchausen
writeln "Answers: ", wherefilter fn f(.n): .n == .spod(.n), series 10..5000</lang>
</syntaxhighlight>
 
{{out}}
<pre>Answers: [1, 3435]</pre>
 
=={{header|LDPL}}==
<syntaxhighlight lang="ldpl">data:
d is number
i is number
n is number
sum is number
 
procedure:
for i from 1 to 5001 step 1 do
store 0 in sum
store i in n
while n is greater than 0 do
modulo n by 10 in d
raise d to d in d
add sum and d in sum
divide n by 10 in n
floor n
repeat
if sum is equal to i then
display i lf
end if
repeat
</syntaxhighlight>
{{out}}
<pre>
1
3435
</pre>
 
=={{header|Lua}}==
<langsyntaxhighlight Lualang="lua">function isMunchausen (n)
local sum, nStr, digit = 0, tostring(n)
for pos = 1, #nStr do
digit = tonumber(nStr:sub(pos, pos))
sum = sum + digit ^ digit
end
return sum == n
end
 
-- alternative, faster version based on the C version,
-- avoiding string manipulation, for Lua 5.3 or higher
local function isMunchausen (n)
local sum, digit, acc = 0, 0, n
while acc > 0 do
digit = acc % 10.0
sum = sum + digit ^ digit
acc = acc // 10 -- integer div
end
return sum == n
Line 1,136 ⟶ 1,825:
for i = 1, 5000 do
if isMunchausen(i) then print(i) end
end</langsyntaxhighlight>
{{out}}
<pre>1
3435</pre>
 
=={{header|Nim}}==
<lang nim>import math
 
for i in 1..<5000:
var sum: int64 = 0
var number = i
while number > 0:
var digit = number mod 10
sum += digit ^ digit
number = number div 10
if sum == i:
echo i</lang>
{{out}}
<pre>1
Line 1,158 ⟶ 1,831:
 
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Munchausen {
Inventory p=0:=0,1:=1
Line 1,177 ⟶ 1,850:
}
Munchausen
</syntaxhighlight>
</lang>
Using Array instead of Inventory
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Münchhausen {
Dim p(0 to 9)
Line 1,199 ⟶ 1,872:
}
Münchhausen
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,205 ⟶ 1,878:
</pre>
 
=={{header|MathematicaMAD}}==
<syntaxhighlight lang="mad"> NORMAL MODE IS INTEGER
<lang Mathematica>Off[Power::indet];(*Supress 0^0 warnings*)
DIMENSION P(5)
Select[Range[5000], Total[IntegerDigits[#]^IntegerDigits[#]] == # &]</lang>
THROUGH CLCPOW, FOR D=0, 1, D.G.5
P(D) = D
THROUGH CLCPOW, FOR X=1, 1, X.GE.D
CLCPOW P(D) = P(D) * D
 
THROUGH TEST, FOR D1=0, 1, D1.G.5
THROUGH TEST, FOR D2=0, 1, D2.G.5
THROUGH TEST, FOR D3=0, 1, D3.G.5
THROUGH TEST, FOR D4=1, 1, D4.G.5
N = D1*1000 + D2*100 + D3*10 + D4
WHENEVER P(D1)+P(D2)+P(D3)+P(D4) .E. N
PRINT FORMAT FMT,N
TEST END OF CONDITIONAL
 
VECTOR VALUES FMT = $I4*$
END OF PROGRAM </syntaxhighlight>
 
{{out}}
 
<pre> 1
3435</pre>
 
=={{header|Maple}}==
<syntaxhighlight lang="maple">isMunchausen := proc(n::posint)
local num_digits;
num_digits := map(x -> StringTools:-Ord(x) - 48, StringTools:-Explode(convert(n, string)));
return evalb(n = convert(map(x -> x^x, num_digits), `+`));
end proc;
 
Munchausen_upto := proc(n::posint) local k, count, list_num;
list_num := [];
for k to n do
if isMunchausen(k) then
list_num := [op(list_num), k];
end if;
end do;
return list_num;
end proc;
 
Munchausen_upto(5000);</syntaxhighlight>
{{out}}
<pre>[1, 3435]</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">Off[Power::indet];(*Supress 0^0 warnings*)
Select[Range[5000], Total[IntegerDigits[#]^IntegerDigits[#]] == # &]</syntaxhighlight>
{{out}}
<pre>{1,3435}</pre>
Line 1,213 ⟶ 1,933:
=={{header|min}}==
{{works with|min|0.19.3}}
<langsyntaxhighlight lang="min">(dup string "" split (int dup pow) (+) map-reduce ==) :munchausen?
1 :i
(i 5000 <=) ((i munchausen?) (i puts!) when i succ @i) while</langsyntaxhighlight>
{{out}}
<pre>
Line 1,223 ⟶ 1,943:
 
=={{header|Modula-2}}==
<langsyntaxhighlight lang="modula2">MODULE MunchausenNumbers;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,ReadChar;
Line 1,268 ⟶ 1,988:
 
ReadChar;
END MunchausenNumbers.</langsyntaxhighlight>
 
=={{header|Nim}}==
<syntaxhighlight lang="nim">import math
 
for i in 1..<5000:
var sum: int64 = 0
var number = i
while number > 0:
var digit = number mod 10
sum += digit ^ digit
number = number div 10
if sum == i:
echo i</syntaxhighlight>
{{out}}
<pre>1
3435</pre>
 
=={{header|OCaml}}==
<syntaxhighlight lang="ocaml">let is_munchausen n =
let pwr = [|1; 1; 4; 27; 256; 3125; 46656; 823543; 16777216; 387420489|] in
let rec aux x = if x < 10 then pwr.(x) else aux (x / 10) + pwr.(x mod 10) in
n = aux n
 
let () =
Seq.(ints 1 |> take 5000 |> filter is_munchausen |> iter (Printf.printf " %u"))
|> print_newline</syntaxhighlight>
{{out}}
<pre> 1 3435</pre>
 
=={{header|Pascal}}==
Line 1,275 ⟶ 2,023:
tried to speed things up.Only checking one arrangement of 123456789 instead of all 9! = 362880 permutations.This ist possible, because summing up is commutative.
So I only have to create [http://rosettacode.org/wiki/Combinations_with_repetitions Combinations_with_repetitions] and need to check, that the number and the sum of power of digits have the same amount in every possible digit. This means, that a combination of the digits of number leads to the sum of power of digits. Therefore I need leading zero's.
<langsyntaxhighlight lang="pascal">{$IFDEF FPC}{$MODE objFPC}{$ELSE}{$APPTYPE CONSOLE}{$ENDIF}
uses
sysutils;
Line 1,347 ⟶ 2,095:
writeln('Check Count ',cnt);
end.
</syntaxhighlight>
</lang>
{{Out}}
<pre> 1 000000001
Line 1,360 ⟶ 2,108:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">use List::Util "sum";
for my $n (1..5000) {
print "$n\n" if $n == sum( map { $_**$_ } split(//,$n) );
}</langsyntaxhighlight>
{{out}}
<pre>1
3435</pre>
 
=={{header|Perl 6}}==
<lang perl6>sub is_munchausen ( Int $n ) {
constant @powers = 0, |map { $_ ** $_ }, 1..9;
$n == @powers[$n.comb].sum;
}
.say if .&is_munchausen for 1..5000;</lang>
{{out}}
<pre>1
Line 1,379 ⟶ 2,117:
 
=={{header|Phix}}==
<!--(phixonline)-->
<lang Phix>sequence powers = 0&sq_power(tagset(9),tagset(9))
<syntaxhighlight lang="phix">
 
with javascript_semantics
constant powers = sq_power(tagset(9),tagset(9))
function munchausen(integer n)
integer n0 = n
atom summtotal = 0
while n!=0 do
summinteger r += powers[remainder(n,10)+1]
if r then total += powers[r] end if
n = floor(n/10)
end while
return summ(total==n0)
end function
 
for i=1m toin tagset(5000) & 438579088 do
if munchausen(im) then ?im end if
end for</lang>
</syntaxhighlight>
{{out}}
Checking every number between 5,000 and 438,579,088 would take/waste a couple of minutes, and it wouldn't prove anything unless it went to 99,999,999,999 which would take a ''very'' long time!
<pre>
1
3435
438579088
</pre>
=== Alternative ===
<syntaxhighlight lang="phix">
function munchausen(integer lo, maxlen)
string digits = sprint(lo)
sequence res = {}
integer count = 0, l = length(digits)
atom lim = power(10,l), lom = 0
while length(digits)<=maxlen do
count += 1
atom tot = 0
for j=1 to length(digits) do
integer d = digits[j]-'0'
if d then tot += power(d,d) end if
end for
if tot>=lom and tot<=lim and sort(sprint(tot))=digits then
res &= tot
end if
for j=length(digits) to 0 by -1 do
if j=0 then
digits = repeat('0',length(digits)+1)
lim *= 10
lom = (lom+1)*10-1
exit
elsif digits[j]<'9' then
digits[j..$] = digits[j]+1
exit
end if
end for
end while
return {count,res}
end function
atom t0 = time()
printf(1,"Munchausen 1..4 digits (%d combinations checked): %v\n",munchausen(1,4))
printf(1,"All Munchausen, 0..11 digits (%d combinations): %v\n",munchausen(0,11))
?elapsed(time()-t0)
</syntaxhighlight>
{{out}}
<pre>
Munchausen 1..4 digits (999 combinations checked): {1,3435}
All Munchausen, 0..11 digits (352715 combinations): {0,1,3435,438579088}
"0.3s"
</pre>
 
=={{header|PHP}}==
<syntaxhighlight lang="php">
<?php
 
$pwr = array_fill(0, 10, 0);
 
function isMunchhausen($n)
{
global $pwr;
$sm = 0;
$temp = $n;
while ($temp) {
$sm= $sm + $pwr[($temp % 10)];
$temp = (int)($temp / 10);
}
return $sm == $n;
}
 
for ($i = 0; $i < 10; $i++) {
$pwr[$i] = pow((float)($i), (float)($i));
}
 
for ($i = 1; $i < 5000 + 1; $i++) {
if (isMunchhausen($i)) {
echo $i . PHP_EOL;
}
}</syntaxhighlight>
{{out}}
<pre>
1
3435</pre>
 
=={{header|Picat}}==
<syntaxhighlight lang="picat">go =>
println([N : N in 1..5000, munchhausen_number(N)]).
 
munchhausen_number(N) =>
N == sum([T : I in N.to_string(),II = I.to_int(), T = II**II]).</syntaxhighlight>
 
{{out}}
<pre>[1,3435]</pre>
 
Testing for a larger interval, 1..500 000 000, requires another approach:
<syntaxhighlight lang="picat">go2 ?=>
H = [0] ++ [I**I : I in 1..9],
N = 1,
while (N < 500_000_000)
Sum = 0,
NN = N,
Found = true,
while (NN > 0, Found == true)
Sum := Sum + H[1+(NN mod 10)],
if Sum > N then
Found := false
end,
NN := NN div 10
end,
if Sum == N then
println(N)
end,
N := N+1
end,
nl.
</syntaxhighlight>
 
{{out}}
<pre>1
3435
438579088</pre>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(for N 5000
(and
(=
Line 1,408 ⟶ 2,265:
'((N) (** N N))
(mapcar format (chop N)) ) )
(println N) ) )</langsyntaxhighlight>
{{out}}
<pre>
1
3435</pre>
 
=={{header|PL/I}}==
<syntaxhighlight lang="pli">munchausen: procedure options(main);
/* precalculate powers */
declare (pows(0:5), i) fixed;
pows(0) = 0; /* 0^0=0 for Munchausen numbers */
do i=1 to 5; pows(i) = i**i; end;
declare (d1, d2, d3, d4, num, dpow) fixed;
do d1=0 to 5;
do d2=0 to 5;
do d3=0 to 5;
do d4=1 to 5;
num = d1*1000 + d2*100 + d3*10 + d4;
dpow = pows(d1) + pows(d2) + pows(d3) + pows(d4);
if num=dpow then put skip list(num);
end;
end;
end;
end;
end munchausen;</syntaxhighlight>
{{out}}
<pre> 1
3435</pre>
 
=={{header|Plain English}}==
<syntaxhighlight lang="plainenglish">To run:
Start up.
Show the Munchausen numbers up to 5000.
Wait for the escape key.
Shut down.
 
To show the Munchausen numbers up to a number:
If a counter is past the number, exit.
If the counter is Munchausen, convert the counter to a string; write the string to the console.
Repeat.
 
To decide if a number is Munchausen:
Privatize the number.
Find the sum of the digit self powers of the number.
If the number is the original number, say yes.
Say no.
 
To find the sum of the digit self powers of a number:
If the number is 0, exit.
Put 0 into a sum number.
Loop.
Divide the number by 10 giving a quotient and a remainder.
Put the quotient into the number.
Raise the remainder to the remainder.
Add the remainder to the sum.
If the number is 0, break.
Repeat.
Put the sum into the number.</syntaxhighlight>
{{out}}
<pre>
1
3435
</pre>
 
=={{header|PowerBASIC}}==
{{trans|FreeBASIC}}(Translated from the FreeBasic Version 2 example.)
<langsyntaxhighlight lang="powerbasic">#COMPILE EXE
#DIM ALL
#COMPILER PBCC 6
Line 1,488 ⟶ 2,404:
CON.PRINT "execution time:" & STR$(t) & " ms; hit any key to end program"
CON.WAITKEY$
END FUNCTION</langsyntaxhighlight>
{{out}}
<pre> 0
Line 1,497 ⟶ 2,413:
 
=={{header|Pure}}==
<langsyntaxhighlight Purelang="pure">// split numer into digits
digits n::number = loop n [] with
loop n l = loop (n div 10) ((n mod 10):l) if n > 0;
Line 1,507 ⟶ 2,423:
(map (\d -> d^d)
(digits n)); end;
munchausen 5000;</langsyntaxhighlight>
{{out}}
<pre>[1,3435]</pre>
Line 1,513 ⟶ 2,429:
=={{header|PureBasic}}==
{{trans|C}}
<langsyntaxhighlight PureBasiclang="purebasic">EnableExplicit
Declare main()
 
Line 1,537 ⟶ 2,453:
EndIf
Next
EndProcedure</langsyntaxhighlight>
{{out}}
<pre>1
Line 1,543 ⟶ 2,459:
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">for i in range(5000):
if i == sum(int(x) ** int(x) for x in str(i)):
print(i)</langsyntaxhighlight>
{{out}}
<pre>1
Line 1,556 ⟶ 2,472:
 
{{Works with|Python|3}}
<langsyntaxhighlight lang="python">'''Munchausen numbers'''
 
from functools import (reduce)
Line 1,611 ⟶ 2,527:
 
if __name__ == '__main__':
main()</langsyntaxhighlight>
<pre>[1, 3435]</pre>
 
=={{header|RacketQuackery}}==
<syntaxhighlight lang="quackery"> [ dup 0 swap
[ dup 0 != while
10 /mod dup **
rot + swap again ]
drop = ] is munchausen ( n --> b )
 
5000 times
<lang>#lang racket
[ i^ 1+ munchausen if
[ i^ 1+ echo sp ] ]</syntaxhighlight>
 
{{out}}
 
<pre>1 3435 </pre>
 
=={{header|Racket}}==
<syntaxhighlight lang="text">#lang racket
 
(define (expt:0^0=1 r p)
Line 1,641 ⟶ 2,571:
(check-true (munchausen-number? 3435))
(check-false (munchausen-number? 3))
(check-false (munchausen-number? -45) "no recursion on -ve numbers"))</langsyntaxhighlight>
 
{{out}}
<pre>1
3435</pre>
 
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" line>sub is_munchausen ( Int $n ) {
constant @powers = 0, |map { $_ ** $_ }, 1..9;
$n == @powers[$n.comb].sum;
}
.say if .&is_munchausen for 1..5000;</syntaxhighlight>
{{out}}
<pre>1
Line 1,649 ⟶ 2,590:
=={{header|REXX}}==
===version 1===
<langsyntaxhighlight lang="rexx">Do n=0 To 10000
If n=m(n) Then
Say n
Line 1,660 ⟶ 2,601:
res=res+c**c
End
Return res</langsyntaxhighlight>
{{out}}
<pre>D:\mau>rexx munch
Line 1,670 ⟶ 2,611:
This REXX version uses the requirement that &nbsp; '''0**0''' &nbsp; equals zero.
 
It is about &nbsp; '''2.5''' &nbsp; times faster than REXX version 1.
 
For the high limit of &nbsp; '''5,000''', &nbsp; optimization isn't needed. &nbsp; But for much higher limits, optimization becomes significant.
<langsyntaxhighlight lang="rexx">/*REXX program finds and displays Münchhausen numbers from one to a specified number (Z)*/
@.= 0; do i=1 for 9; @.i= i**i; end /*precompute powers for non-zero digits*/
parse arg z . /*obtain optional argument from the CL.*/
if z=='' | z=="," then z=5000 5000 /*Not specified? Then use the default.*/
@is='is a Münchhausen number.'; do j=1 for z /* [↓] traipse through all the numbers*/
if isMunch(j) then say right(j, 11) @is
Line 1,682 ⟶ 2,623:
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
isMunch: parse arg x 1 ox; $= 0; do until x=='' | $>ox /*stop if too large.*/
parse var x _ +1 x; $= $ + @._ /*add the next power*/
end /*while*/ /* [↑] get a digit.*/
return $==ox /*it is or it ain't.*/</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default input:}}
'''output'''
<pre>
1 is a Münchhausen number.
Line 1,693 ⟶ 2,634:
 
===version 3===
It is about &nbsp; '''3''' &nbsp; times faster than REXX version 1.
<langsyntaxhighlight lang="rexx">/*REXX program finds and displays Münchhausen numbers from one to a specified number (Z)*/
@.= 0; do i=1 for 9; @.i= i**i; end /*precompute powers for non-zero digits*/
parse arg z . /*obtain optional argument from the CL.*/
if z=='' | z=="," then z=5000 5000 /*Not specified? Then use the default.*/
@is='is a Münchhausen number.'; do j=1 for z /* [↓] traipse through all the numbers*/
if isMunch(j) then say right(j, 11) @is
Line 1,706 ⟶ 2,647:
if $>ox then return 0 /*is sum too large?*/
do while x\=='' & $<=ox /*any more digits ?*/
parse var x _ +1 x; $= $ + @._ /*sum 6th & up digs*/
end /*while*/
return $==ox /*it is or it ain't*/</langsyntaxhighlight>
'''{{out|output''' |text=&nbsp; is the same as the 2<sup>nd</sup> REXX version.}} <br><br>
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Munchausen numbers
 
Line 1,728 ⟶ 2,669:
ok
next
</syntaxhighlight>
</lang>
Output:
<pre>
Line 1,735 ⟶ 2,676:
</pre>
 
=={{header|RPL}}==
≪ { } 1 5000 '''FOR''' j
j →STR DUP SIZE 0 1 ROT '''FOR''' k
OVER k DUP SUB STR→ DUP ^ +
'''NEXT'''
SWAP DROP
'''IF''' j == '''THEN''' j + '''END'''
'''NEXT'''
EVAL
{{out}}
<pre>
1: { 1 3435 }
</pre>
=={{header|Ruby}}==
<syntaxhighlight lang="ruby"> puts (1..5000).select{|n| n.digits.sum{|d| d**d} == n}</syntaxhighlight>
<lang ruby>class Integer
 
def munchausen?
self.digits.map{|d| d**d}.sum == self
end
 
end
 
puts (1..5000).select(&:munchausen?)</lang>
{{out}}
<pre>
Line 1,752 ⟶ 2,699:
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">fn main() {
let mut solutions = Vec::new();
 
Line 1,770 ⟶ 2,717:
 
println!("Munchausen numbers below 5_000 : {:?}", solutions);
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,778 ⟶ 2,725:
=={{header|Scala}}==
Adapted from Zack Denton's code posted on [https://zach.se/munchausen-numbers-and-how-to-find-them/ Munchausen Numbers and How to Find Them].
<syntaxhighlight lang="scala">
<lang Scala>
object Munch {
def main(args: Array[String]): Unit = {
Line 1,788 ⟶ 2,735:
}
}
</syntaxhighlight>
</lang>
{{out}}
<pre>1 (munchausen)
3435 (munchausen)</pre>
 
=={{header|SETL}}==
<syntaxhighlight lang="setl">program munchausen_numbers;
loop for n in [1..5000] | munchausen n do
print(n);
end loop;
 
op munchausen(n);
m := n;
loop while m>0 do
d := m mod 10;
m div:= 10;
sum +:= d ** d;
end loop;
return sum = n;
end op;
end program;</syntaxhighlight>
{{out}}
<pre>1
3435</pre>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">func is_munchausen(n) {
n.digits.map{|d| d**d }.sum == n
}
 
say (1..5000 -> grep(is_munchausen))</langsyntaxhighlight>
{{out}}
<pre>
Line 1,805 ⟶ 2,772:
 
=={{header|SuperCollider}}==
<langsyntaxhighlight lang="supercollider">(1..5000).select { |n| n == n.asDigits.sum { |x| pow(x, x) } }</langsyntaxhighlight>
 
<pre>
Line 1,812 ⟶ 2,779:
 
=={{header|Swift}}==
<langsyntaxhighlight lang="swift">import Foundation
 
func isMünchhausen(_ n: Int) -> Bool {
Line 1,822 ⟶ 2,789:
for i in 1...5000 where isMünchhausen(i) {
print(i)
}</langsyntaxhighlight>
{{out}}
<pre>1
3435</pre>
 
=={{header|Symsyn}}==
<syntaxhighlight lang="symsyn">
x : 10 1
(2^2) x.2
(3^3) x.3
(4^4) x.4
(5^5) x.5
(6^6) x.6
(7^7) x.7
(8^8) x.8
(9^9) x.9
 
1 i
if i <= 5000
~ i $i | convert binary to string
#$i j | length to j
y | set y to 0
if j > 0
$i.j $j 1 | move digit j to string j
~ $j n | convert j string to binary
+ x.n y | add value x at n to y
- j | dec j
goif
endif
if i = y
i [] | output to console
endif
+ i
goif
endif
 
</syntaxhighlight>
{{out}}
<pre>1
3435</pre>
=={{header|TI-83 BASIC}}==
{{works with|TI-83 BASIC|TI-84Plus 2.55MP}}
{{trans|Fortran}}
<langsyntaxhighlight lang="ti83b"> For(I,1,5000)
0→S:I→K
For(J,1,4)
Line 1,840 ⟶ 2,844:
End
If S=I:Disp I
End </langsyntaxhighlight>
{{out}}
<pre>
Line 1,848 ⟶ 2,852:
Execution time: 15 min
 
===Optimized Version===
=={{header|VBA}}==
{{trans|BASIC}}
This takes advantage of the fact that N^N > 9999 for any single digit natural number N where N > 6. It also uses a look up table for powers to allow the assumption that 0^0 = 1.
<syntaxhighlight lang="ti83b">{1,1,4,27,256,3125}→L₁
For(A,0,5,1)
For(B,0,5,1)
For(C,0,5,1)
For(D,0,5,1)
A*1000+B*100+C*10+D→N
L₁(D+1)→M
If N≥10
M+L₁(C+1)→M
If N≥100
M+L₁(B+1)→M
If N≥1000
M+L₁(A+1)→M
If N=M
Disp N
End
End
End
End</syntaxhighlight>
{{out}}
<pre>
1
3435
</pre>
Execution time: 2 minutes 20 seconds
 
=={{header|VBA}}==
<lang vb>
<syntaxhighlight lang="vb">
Option Explicit
 
Line 1,870 ⟶ 2,902:
IsMunchausen = (Tot = Number)
End Function
</syntaxhighlight>
</lang>
{{out}}
<pre>1 is a munchausen number.
Line 1,876 ⟶ 2,908:
 
=={{header|VBScript}}==
<langsyntaxhighlight lang="vbscript">
for i = 1 to 5000
if Munch(i) Then
Line 1,902 ⟶ 2,934:
 
End Function
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,911 ⟶ 2,943:
=={{header|Visual Basic}}==
{{trans|FreeBASIC}}(Translated from the FreeBasic Version 2 example.)
<langsyntaxhighlight lang="vb">Option Explicit
 
Declare Function GetTickCount Lib "kernel32.dll" () As Long
Line 2,017 ⟶ 3,049:
res = res & "execution time:" & Str$(t) & " ms"
MsgBox res
End Sub</langsyntaxhighlight>
{{out}}
<pre> 0
Line 2,028 ⟶ 3,060:
{{trans|FreeBASIC}}(Translated from the FreeBasic Version 2 example.)<br/>
Computation time is under 4 seconds on tio.run.
<langsyntaxhighlight lang="vbnet">Imports System
 
Module Program
Line 2,052 ⟶ 3,084:
Next
End Sub
End Module</langsyntaxhighlight>
{{out}}
<pre>0
Line 2,058 ⟶ 3,090:
3435
438579088</pre>
 
=={{header|Wren}}==
<syntaxhighlight lang="wren">var powers = List.filled(10, 0)
for (i in 1..9) powers[i] = i.pow(i).round // cache powers
 
var munchausen = Fn.new {|n|
if (n <= 0) Fiber.abort("Argument must be a positive integer.")
var nn = n
var sum = 0
while (n > 0) {
var digit = n % 10
sum = sum + powers[digit]
n = (n/10).floor
}
return nn == sum
}
 
System.print("The Munchausen numbers <= 5000 are:")
for (i in 1..5000) {
if (munchausen.call(i)) System.print(i)
}</syntaxhighlight>
 
{{out}}
<pre>
The Munchausen numbers <= 5000 are:
1
3435
</pre>
 
=={{header|XPL0}}==
The digits 6, 7, 8 and 9 can't occur because 6^6 = 46656, which is beyond 5000.
<syntaxhighlight lang="xpl0">int Pow, A, B, C, D, N;
[Pow:= [0, 1, 4, 27, 256, 3125];
for A:= 0 to 5 do
for B:= 0 to 5 do
for C:= 0 to 5 do
for D:= 0 to 5 do
[N:= A*1000 + B*100 + C*10 + D;
if Pow(A) + Pow(B) + Pow(C) + Pow(D) = N then
if N>=1 & N<= 5000 then
[IntOut(0, N); CrLf(0)];
];
]</syntaxhighlight>
 
{{out}}
<pre>
1
3435
</pre>
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">[1..5000].filter(fcn(n){ n==n.split().reduce(fcn(s,n){ s + n.pow(n) },0) })
.println();</langsyntaxhighlight>
{{out}}
<pre>
890

edits