Project Euler | | Soru 10

0 Cevap php

PHP Proje Euler çözmeye çalışırken ve döngü içindeyken döngü koşulları benim bir sorun haline çalıştırıyorum. Birisi doğru yönde bana gelin? Ben burada doğru yolda mıyım?

Sorun, btw, 2,000,000 altındaki tüm asal sayıların toplamları bulmaktır

Diğer not: Ben karşılaşmış değilim sorun bellek domuz gibi görünüyor ve elek uygulanması yanında, ben bu yaklaşım başka nasıl emin değilim ki. Ben uygulanmasında yanlış bir şey yaptıysa, ben merak ediyorum.

<?php

// The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
// Additional information:
//   Sum below 100: 1060 
//        1000: 76127
//  (for testing)

// Find the sum of all the primes below 2,000,000.

// First, let's set n = 2 mill or the number we wish to find
// the primes under.

$n = 2000000;

// Then, let's set p = 2, the first prime number.

$p = 2;

// Now, let's create a list of all numbers from p to n.

$list = range($p, $n);

// Now the loop for Sieve of Eratosthenes.
// Also, let $i = 0 for a counter.

$i = 0;

while($p*$p < $n)
{
// Strike off all multiples of p less than or equal to n

  for($k=0; $k < $n; $k++)
  { 
      if($list[$k] % $p == 0)
      {
         unset($list[$k]);
      }
  }

 // Re-initialize array

 sort ($list);

 // Find first number on list after p. Let that equal p.

 $i = $i + 1;

 $p = $list[$i];

 }

 echo array_sum($list);

?>

0 Cevap