---
title: "Create a function to check if a given number is a perfect number or not using Rust."  
description: "Create a function to check if a given number is a perfect number or not using Rust."  
author: "Utpal Vishwas"  
published: 2023-06-20  
updated: 2023-06-23  
canonical: https://www.mindstick.com/forum/158803/create-a-function-to-check-if-a-given-number-is-a-perfect-number-or-not-using-rust  
category: "rust"  
tags: ["rust"]  
reading_time: 2 minutes  

---

# Create a function to check if a given number is a perfect number or not using Rust.

Create a [function to check](https://www.mindstick.com/forum/161900/write-a-function-to-check-if-a-number-is-prime-with-explanation) if a given number is a perfect number or not using Rust.

## Replies

### Reply by Aryan Kumar

Sure, here is a Rust [function](https://www.mindstick.com/articles/13001/multi-statement-table-valued-user-defined-function-in-sql-server) to [check if](https://www.mindstick.com/forum/12878/how-to-check-if-an-asp-dot-net-file-upload-control-has-a-file-in-jquery) a given number is a perfect number or not:

Rust

```plaintext
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

```plaintext
rustc is_perfect_number.rs
```

Once the program is compiled, you can run it using the following command:

Code snippet

```plaintext
./is_perfect_number
```

This will print the following output to the console:

Code snippet

```plaintext
The number 6 is a perfect number: true
```


---

Original Source: https://www.mindstick.com/forum/158803/create-a-function-to-check-if-a-given-number-is-a-perfect-number-or-not-using-rust

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
