How to resolve the algorithm Iterated digits squaring step by step in the Rust programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Iterated digits squaring step by step in the Rust programming language
Table of Contents
Problem Statement
If you add the square of the digits of a Natural number (an integer bigger than zero), you always end with either 1 or 89: An example in Python:
Or, for much less credit - (showing that your algorithm and/or language is slow): This problem derives from the Project Euler problem 92. For a quick algorithm for this task see the talk page
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Iterated digits squaring step by step in the Rust programming language
Source code in the rust programming language
fn digit_square_sum(mut num: usize) -> usize {
let mut sum = 0;
while num != 0 {
sum += (num % 10).pow(2);
num /= 10;
}
sum
}
fn last_in_chain(num: usize) -> usize {
match num {
1 | 89 => num,
_ => last_in_chain(digit_square_sum(num)),
}
}
fn main() {
let count = (1..100_000_000).filter(|&n| last_in_chain(n) == 89).count();
println!("{}", count);
}
fn dig_sq_sum(mut num : usize ) -> usize {
let mut sum = 0;
while num != 0 {
sum += (num % 10).pow(2);
num /= 10;
}
sum
}
fn last_in_chain(num: usize) -> usize {
match num {
0 => 0,
1 | 89 => num,
_ => last_in_chain(dig_sq_sum(num)),
}
}
fn main() {
let prec: Vec<_> = (0..649).map(|n| last_in_chain(n)).collect();
let count = (1..100_000_000).filter(|&n| prec[dig_sq_sum(n)] == 89).count();
println!("{}", count);
}
You may also check:How to resolve the algorithm Box the compass step by step in the AutoIt programming language
You may also check:How to resolve the algorithm Superellipse step by step in the Kotlin programming language
You may also check:How to resolve the algorithm Digital root/Multiplicative digital root step by step in the Raku programming language
You may also check:How to resolve the algorithm File input/output step by step in the Objeck programming language
You may also check:How to resolve the algorithm Literals/Integer step by step in the PL/I programming language