djmattyg007

Project Euler Problem 3 - does not actually work

Sep 30th, 2013
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.04 KB | None | 0 0
  1. #!/usr/bin/php
  2. <?php
  3.  
  4. function isPrime($num) {
  5.     if (!is_numeric($num)) {
  6.         exit(1);
  7.     } elseif ($num < 1) {
  8.         exit(2);
  9.     } elseif ($num == 1) {
  10.         return false;
  11.     }
  12.  
  13.     $half = ceil(($num / 2) + 1);
  14.     for ($x = 2; $x < $half; $x++) {
  15.         if ($num % $x == 0) {
  16.             return false;
  17.         }
  18.     }
  19.     return true;
  20. }
  21.  
  22. function getFactors($num) {
  23.     if (!is_numeric($num)) {
  24.         exit(3);
  25.     } elseif ($num < 1) {
  26.         exit(4);
  27.     } elseif ($num == 1) {
  28.         return array(1);
  29.     }
  30.  
  31.     $factors = array();
  32.     echo "number: \t$num\n";
  33.     for ($x = 1; $x <= $num; $x++) {
  34.         if ($num % $x == 0) {
  35.             $factors[] = $x;
  36.             echo "new factor:\t$x\n";
  37.         }
  38.     }
  39.     return $factors;
  40. }
  41. echo("start: " . ($start = time()) . "\n");
  42. $factors = getFactors(600851475143);
  43. echo("end:   " . ($end = time()) . "\n");
  44. echo("total: " . ($end - $start));
  45.  
  46. echo($start = time() . "\n");
  47. foreach ($factors as $factor) {
  48.     echo $factor . ": \t";
  49.     if (isPrime($factor)) {
  50.         echo "prime\n";
  51.     } else {
  52.         echo "not prime\n";
  53.     }
  54. }
  55. echo($end = time() . "\n");
  56. echo("total: " . ($end - $start));
Advertisement
Add Comment
Please, Sign In to add comment