DEV Community

loading...

Discussion on: Narcissistic number

Collapse
kip13 profile image
kip

I'm learning Rust and this challenge looks good to practice, this is my solution.

fn main() {
  for number in 0..1000 {
    if is_narcissistic(number) {
      println!("{} is narcissistic", number);
    }
  }
}

fn is_narcissistic(number: i32) -> bool {
  digits_pow(number) == number
}

fn digits_pow(mut number: i32) -> i32 {
  let digits= (number as f64).log10()
    .floor() + 1_f64;

  let mut sum = 0;

  while number != 0 {
    sum += ((number % 10)).pow(digits as u32);
    number = ((number / 10) as f64).floor() as i32;
  }

  sum
}
0 is narcissistic
1 is narcissistic
2 is narcissistic
3 is narcissistic
4 is narcissistic
5 is narcissistic
6 is narcissistic
7 is narcissistic
8 is narcissistic
9 is narcissistic
153 is narcissistic
370 is narcissistic
371 is narcissistic
407 is narcissistic