Rosetta Code

Narcissistic decimal number

Identify fixed sample numbers that equal the sum of their digits raised to the digit count.

Intro View source
Source rosettacode/popular/narcissistic_decimal_number.vibe
# title: Narcissistic decimal number
# source: https://rosettacode.org/wiki/Narcissistic_decimal_number
# category: Rosetta Code
# difficulty: Intro
# summary: Identify fixed sample numbers that equal the sum of their digits raised to the digit count.
# tags: popular, numbers, math, search
# vibe: 0.2

def digit_value(char)
  "0123456789".index(char)
end

def power(base, exponent)
  value = 1
  count = 0

  while count < exponent
    value = value * base
    count = count + 1
  end

  value
end

def narcissistic?(value)
  digits = "" + value
  length = digits.length
  total = 0
  index = 0

  while index < length
    total = total + power(digit_value(digits.slice(index)), length)
    index = index + 1
  end

  total == value
end

def run
  [
    { value: 153, narcissistic: narcissistic?(153) },
    { value: 370, narcissistic: narcissistic?(370) },
    { value: 407, narcissistic: narcissistic?(407) },
    { value: 408, narcissistic: narcissistic?(408) }
  ]
end
Output
Press run to execute run from this example.
rosetta-code popular numbers math search browser-runner