How to check if a number is a happy number in Rust

1 Answer

0 votes
use std::collections::HashSet;

// 8^2 + 2^2 = 68
// 6^2 + 8^2 = 100
// 1^2 + 0^2 + 0^2 = 1 = happy number

fn sum_of_squares(mut n: i32) -> i32 {
    let mut sum = 0;
    while n > 0 {
        let d = n % 10;
        sum += d * d;
        n /= 10;
    }
    sum
}

fn is_happy(mut n: i32) -> bool {
    let mut seen = HashSet::new();

    while n != 1 && !seen.contains(&n) {
        seen.insert(n);
        n = sum_of_squares(n);
    }

    n == 1
}

fn main() {
    let num = 82;

    if is_happy(num) {
        println!("{num} is a happy number");
    } else {
        println!("{num} is NOT a happy number");
    }
}

  
   
/*
run:
   
82 is a happy number
  
*/

 



answered Feb 23 by avibootz
edited Feb 24 by avibootz
...