Rust Program to Check Armstrong Number


Check Armstrong Number

Rust Programming Language


Check Armstrong Number


Problem


Rust program that checks whether a given number is an Armstrong number or not.

Input


use std::io;

fn main() {
    println!("Please enter a positive integer:");

    let mut input = String::new();
    io::stdin()
        .read_line(&mut input)
        .expect("Failed to read line");

    let input = input.trim().parse::<u32>().unwrap();

    let mut sum = 0;
    let mut n = input;
    let mut digits = Vec::new();
    while n > 0 {
        digits.push(n % 10);
        n /= 10;
    }

    let num_digits = digits.len() as u32;
    for digit in digits {
        sum += digit.pow(num_digits);
    }

    if sum == input {
        println!("The number {} is an Armstrong number", input);
    } else {
        println!("The number {} is not an Armstrong number", input);
    }
}{codeBox}

Output


Please enter a positive integer:
153
The number 153 is an Armstrong number{codeBox}

Explanation


This program prompts the user to enter a positive integer, reads the input integer from the user using the io module from Rust's standard library, and parses it into an unsigned 32-bit integer using parse::<u32>().unwrap().

We then initialize a variable sum to 0, and a variable n to the input integer. We also initialize an empty vector digits to hold the individual digits of the input integer.

We then loop while n is greater than 0, and in each iteration of the loop, we calculate the remainder of n divided by 10, which gives us the rightmost digit of n. We then append this digit to the digits vector, and divide n by 10 to remove the rightmost digit.

Next, we calculate the number of digits in the input integer using digits.len() as u32, and then iterate over each digit in the digits vector, adding the digit raised to the power of the number of digits to sum.

Finally, we check if sum is equal to the input integer. If it is, we print "The number [input] is an Armstrong number" to the console. Otherwise, we print "The number [input] is not an Armstrong number".

This shows the program prompting the user to enter a positive integer, the user entering the integer 153, and the program checking if the integer is an Armstrong number (which it is), and displaying the appropriate message to the console.

Post a Comment