How to find all happy numbers in a specific range with Rust

1 Answer

0 votes
use std::collections::HashSet;

// A happy number is a number that eventually reaches 1 
// when repeatedly replaced by the sum of the squares of its digits.
//
// 19 = 1^2 + 9^2 = 82
// 19 -> 82 -> 68 ->100 -> 1 eventually reaches 1 
// 19 = happy numbe

// Compute the sum of squares of digits of n
fn sum_of_digit_squares(mut n: i32) -> i32 {
    let mut sum = 0;
    while n > 0 {
        let d = n % 10;
        sum += d * d;
        n /= 10;
    }
    sum
}

// Determine whether n is a happy number
fn is_happy(mut n: i32) -> bool {
    let mut seen: HashSet<i32> = HashSet::new();

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

fn main() {
    let mut a = 1;
    let mut b = 100;

    if a > b {
        std::mem::swap(&mut a, &mut b);
    }

    let mut happy_numbers: Vec<i32> = Vec::new();

    for i in a..=b {
        if is_happy(i) {
            happy_numbers.push(i);
        }
    }

    println!("Happy numbers in range [{}, {}]:", a, b);
    for n in happy_numbers {
        print!("{} ", n);
    }
}



/*
run:

Happy numbers in range [1, 100]:
1 7 10 13 19 23 28 31 32 44 49 68 70 79 82 86 91 94 97 100 

*/

 



answered Feb 25 by avibootz
...