Munchausen numbers: Difference between revisions

From Rosetta Code
Content added Content deleted
(Add JavaScript Code)
Line 57: Line 57:
<pre>1
<pre>1
3435</pre>
3435</pre>

=={{header|zkl}}==
<lang zkl>[1..5000].filter(fcn(n){ n==n.split().reduce(fcn(s,n){ s + n.pow(n) },0) })
.println();</lang>
{{out}}
<pre>
L(1,3435)
</pre>

Revision as of 17:18, 22 September 2016

Munchausen numbers is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.


Definition of Munchausen numbers

A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, is n itself.

Task requirements

Finds all Munchausen numbers between 1 and 5000

C

Adapted from Zack Denton's code posted on Munchausen Numbers and How to Find Them. <lang C>#include <stdio.h>

  1. include <math.h>

int main() {

   for (int i = 1; i < 5000; i++) {
       // loop through each digit in i
       // e.g. for 1000 we get 0, 0, 0, 1.
       int sum = 0;
       for (int number = i; number > 0; number /= 10) {
           int digit = number % 10;
           // find the sum of the digits 
           // raised to themselves 
           sum += pow(digit, digit);
       }
       if (sum == i) {
           // the sum is equal to the number
           // itself; thus it is a 
           // munchausen number
           printf("%i\n", i);
       } 
   }
   return 0;

}</lang>

Output:
1
3435


C#

<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);</lang>

Output:
1
3435

JavaScript

<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);</lang>

Output:
1
3435

zkl

<lang zkl>[1..5000].filter(fcn(n){ n==n.split().reduce(fcn(s,n){ s + n.pow(n) },0) }) .println();</lang>

Output:
L(1,3435)