Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,709 questions

55,473 answers

573 users

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
...