Sure, here is a Rust function to check if a given number is a perfect number or not:
Rust
fn is_perfect_number(number: i32) -> bool {
if number <= 1 {
return false;
}
let mut sum = 1;
for factor in 2..number {
if number % factor == 0 {
sum += factor;
}
}
return sum == number;
}
fn main() {
let number = 6;
let is_perfect_number = is_perfect_number(number);
println!("The number {} is a perfect number: {}", number, is_perfect_number);
}
This function first defines a function called is_perfect_number that takes an i32 number as input and returns a bool. The function first checks if the number is less than or equal to 1. If the number is less than or equal to 1, then the function returns false. Otherwise, the function iterates through the numbers from 2 to the number, adding each factor of the number to a sum variable. Finally, the function returns true if the sum variable is equal to the number.
The main function of the program then creates a number, number, and calls the is_perfect_number function with the number number as input. The result of the function call is then printed to the console.
To run the program, you can save it as a file called is_perfect_number.rs and then compile it using the following command:
Code snippet
rustc is_perfect_number.rs
Once the program is compiled, you can run it using the following command:
Code snippet
./is_perfect_number
This will print the following output to the console:
Code snippet
The number 6 is a perfect number: true
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
Sure, here is a Rust function to check if a given number is a perfect number or not:
Rust
This function first defines a function called is_perfect_number that takes an i32 number as input and returns a bool. The function first checks if the number is less than or equal to 1. If the number is less than or equal to 1, then the function returns false. Otherwise, the function iterates through the numbers from 2 to the number, adding each factor of the number to a sum variable. Finally, the function returns true if the sum variable is equal to the number.
The main function of the program then creates a number, number, and calls the is_perfect_number function with the number number as input. The result of the function call is then printed to the console.
To run the program, you can save it as a file called is_perfect_number.rs and then compile it using the following command:
Code snippet
Once the program is compiled, you can run it using the following command:
Code snippet
This will print the following output to the console:
Code snippet