寻找完美数

  1. pub fn is_perfect_number(num: usize) -> bool {
  2. let mut sum = 0;
  3. for i in 1..num - 1 {
  4. if num % i == 0 {
  5. sum += i;
  6. }
  7. }
  8. num == sum
  9. }
  10. pub fn perfect_numbers(max: usize) -> Vec<usize> {
  11. let mut result: Vec<usize> = Vec::new();
  12. // It is not known if there are any odd perfect numbers, so we go around all the numbers.
  13. for i in 1..max + 1 {
  14. if is_perfect_number(i) {
  15. result.push(i);
  16. }
  17. }
  18. result
  19. }
  20. #[cfg(test)]
  21. mod tests {
  22. use super::*;
  23. #[test]
  24. fn basic() {
  25. assert_eq!(is_perfect_number(6), true);
  26. assert_eq!(is_perfect_number(28), true);
  27. assert_eq!(is_perfect_number(496), true);
  28. assert_eq!(is_perfect_number(8128), true);
  29. assert_eq!(is_perfect_number(5), false);
  30. assert_eq!(is_perfect_number(86), false);
  31. assert_eq!(is_perfect_number(497), false);
  32. assert_eq!(is_perfect_number(8120), false);
  33. assert_eq!(perfect_numbers(10), vec![6]);
  34. assert_eq!(perfect_numbers(100), vec![6, 28]);
  35. assert_eq!(perfect_numbers(496), vec![6, 28, 496]);
  36. assert_eq!(perfect_numbers(1000), vec![6, 28, 496]);
  37. }
  38. }