DEV Community


Discussion on: Narcissistic number

jay profile image

My Rust solution.

fn is_narc(n: i32) -> bool {
  let digits = n.to_string().len() as u32;
  let mut sum = 0;
  let mut m = n;
  while m != 0 {
    sum += (m % 10).pow(digits);
    m /= 10;
  sum == n

// Usage
fn main() {
  (0..=1_000_000)         // upto 1 million
    .filter(|&x| is_narc(x))
    .for_each(|x| println!("{}", x));
kip13 profile image

Good solution!!, but if you test the code here doesnt run, only works in a more updated version no ? What version do you use ?

jay profile image

The inclusive range (..=) that I've used is available from Rust 1.24. It will work with previous versions. But you can change it from (0..=1_000_000) to (0..1_000_001) and it should work in any previous version. uses Rust 1.9, the for_each method for iterator is avalable from 1.21 onwards. You can save the filtered list and call for loop on elements.

Here's the link with formatted code, that will work over there. link

If you want to run the newer version, here's a link to rust playground with the code.

Have fun 😃