质数检测

  1. pub fn prime_check(num: usize) -> bool {
  2. if (num > 1) & (num < 4) {
  3. return true;
  4. } else if (num < 2) || (num % 2 == 0) {
  5. return false;
  6. }
  7. let stop: usize = (num as f64).sqrt() as usize + 1;
  8. for i in (3..stop).step_by(2) {
  9. if num % i == 0 {
  10. return false;
  11. }
  12. }
  13. true
  14. }
  15. #[cfg(test)]
  16. mod tests {
  17. use super::*;
  18. #[test]
  19. fn basic() {
  20. assert_eq!(prime_check(3), true);
  21. assert_eq!(prime_check(7), true);
  22. assert_eq!(prime_check(11), true);
  23. assert_eq!(prime_check(2003), true);
  24. assert_eq!(prime_check(4), false);
  25. assert_eq!(prime_check(6), false);
  26. assert_eq!(prime_check(21), false);
  27. assert_eq!(prime_check(2004), false);
  28. }
  29. }