Created
September 15, 2023 17:12
-
-
Save dimitrilw/b83df1f478a06fad55ea11ede4ea3a23 to your computer and use it in GitHub Desktop.
Rust map-sum vs fold
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* map-sum vs fold | |
This code uses map-sum instead of fold. I find map-sum more readable. | |
In addition, they compile to the same instructions, thus performance | |
should also be identical. | |
Ref: https://godbolt.org/z/v73rW3rdd | |
*/ | |
/// Determine whether the given number is an Armstrong number. | |
/// | |
/// An Armstrong number is a number that is the sum of its own digits, | |
/// each raised to the power of the number of digits in the original number. | |
/// | |
/// # Examples | |
/// | |
/// 153 *is* an Armstrong number, because: | |
/// 1**3 + 5**3 + 3**3 = 1 + 125 + 27 = 153 | |
/// ``` | |
/// let res = armstrong_numbers::is_armstrong_number(153); | |
/// assert!(res); | |
/// ``` | |
/// | |
/// 154 is *not* an Armstrong number, because: | |
/// 1**3 + 5**3 + 4**3 = 1 + 125 + 64 = 190 | |
/// ``` | |
/// let res = armstrong_numbers::is_armstrong_number(154); | |
/// assert!(!res); | |
/// ``` | |
pub fn is_armstrong_number(num: u32) -> bool { | |
let num = u64::from(num); | |
let ln = num.to_string().len() as u32; | |
num == num.to_string() | |
.chars() | |
.map(|c| (c.to_digit(10).unwrap() as u64).pow(ln)) | |
.sum() | |
// num == num.to_string() | |
// .chars() | |
// .fold(0, |acc, c| acc + (c.to_digit(10).unwrap() as u64).pow(ln)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment