Fibonacci.php 931 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  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 is_numeric;
  9. /**
  10. * Validates whether the input follows the Fibonacci integer sequence.
  11. *
  12. * @author Danilo Correa <danilosilva87@gmail.com>
  13. * @author Henrique Moody <henriquemoody@gmail.com>
  14. * @author Samuel Heinzmann <samuel.heinzmann@swisscom.com>
  15. */
  16. final class Fibonacci extends AbstractRule
  17. {
  18. /**
  19. * {@inheritDoc}
  20. */
  21. public function validate($input): bool
  22. {
  23. if (!is_numeric($input)) {
  24. return false;
  25. }
  26. $sequence = [0, 1];
  27. $position = 1;
  28. while ($input > $sequence[$position]) {
  29. ++$position;
  30. $sequence[$position] = $sequence[$position - 1] + $sequence[$position - 2];
  31. }
  32. return $sequence[$position] === (int) $input;
  33. }
  34. }