PrimeNumber.php 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. <?php
  2. /*
  3. * Copyright (c) Alexandre Gomes Gaigalas <alganet@gmail.com>
  4. * SPDX-License-Identifier: MIT
  5. */
  6. declare(strict_types=1);
  7. namespace Respect\Validation\Rules;
  8. use function ceil;
  9. use function is_numeric;
  10. use function sqrt;
  11. /**
  12. * Validates whether the input is a prime number.
  13. *
  14. * @author Alexandre Gomes Gaigalas <alganet@gmail.com>
  15. * @author Camilo Teixeira de Melo <kmilotxm@gmail.com>
  16. * @author Henrique Moody <henriquemoody@gmail.com>
  17. * @author Ismael Elias <ismael.esq@hotmail.com>
  18. * @author Kleber Hamada Sato <kleberhs007@yahoo.com>
  19. */
  20. final class PrimeNumber extends AbstractRule
  21. {
  22. /**
  23. * {@inheritDoc}
  24. */
  25. public function validate($input): bool
  26. {
  27. if (!is_numeric($input) || $input <= 1) {
  28. return false;
  29. }
  30. if ($input != 2 && ($input % 2) == 0) {
  31. return false;
  32. }
  33. for ($i = 3; $i <= ceil(sqrt((float) $input)); $i += 2) {
  34. if ($input % $i == 0) {
  35. return false;
  36. }
  37. }
  38. return true;
  39. }
  40. }