RosettaCodeData/Task/Happy-numbers/Rust/happy-numbers.rs

38 lines
550 B
Rust
Raw Permalink Normal View History

2023-07-01 11:58:00 -04:00
fn sumsqd(mut n: i32) -> i32 {
let mut sq = 0;
while n > 0 {
let d = n % 10;
2026-02-01 16:33:20 -08:00
sq += d * d;
n /= 10;
2023-07-01 11:58:00 -04:00
}
sq
}
2026-02-01 16:33:20 -08:00
fn cycle<T, F>(a: T, f: F) -> T
where
T: Copy + PartialEq,
F: Fn(T) -> T,
{
2023-07-01 11:58:00 -04:00
let mut t = a;
let mut h = f(a);
while t != h {
t = f(t);
2026-02-01 16:33:20 -08:00
h = f(f(h));
2023-07-01 11:58:00 -04:00
}
t
}
fn ishappy(n: i32) -> bool {
cycle(n, sumsqd) == 1
}
fn main() {
2026-02-01 16:33:20 -08:00
let happy: Vec<i32> = (1..)
.filter(|&n| ishappy(n))
.take(8)
.collect();
2023-07-01 11:58:00 -04:00
2026-02-01 16:33:20 -08:00
println!("{:?}", happy);
2023-07-01 11:58:00 -04:00
}