validar suma que programa primos primo primeros numeros numero mostrar los ingresar imprima determinar php arrays math primes

que - suma de primos en php



Una fórmula para encontrar números primos en un bucle (18)

Necesito encontrar números primos con for loop o while loop

Escribí esto, pero esto está mal

<?php $i = 1; while($i<5) { for($j=1; $j<=$i; $j++) { if ($j != 1 && $j != $i) { echo $i . "/" . $j . "=" . $i%$j . "<br />"; if ($i%$j != 0) { echo $i . "<br />"; } } } echo "<br />"; $i += 1; } ?>

¿Hay alguna forma de dividir un número con una matriz para encontrar el restante?


Sin función matemática:

function isPrimeNumber($i) { $n = 2; while ($n < $i) { if ($i % $n) { $n++; continue; } return false; } return true; }


<?php $n = 11; $o = $_POST["maxprime"]; echo ''The script calculated the next primenumbers:</br>''; echo ''2, 3, 5, 7, ''; while (true) { $t = 6; while (true) { if ($n % ($t - 1) == 0) { break; } if ($n % ($t + 1) == 0) { break; } if ($t > sqrt($n)) { echo("$n, "); break; } $t += 6; } if (($n + 1) % 6 == 0) { $n += 2; } else { $n += 4; } if ($n > $o) { break; } } ?>

http://www.primenumbergenerator.com/


Esto, creo, es una rutina bastante eficiente, que enumera todos los números primos hasta 1000.

Prueba cada número ($ x) para ver si tiene algún factor (aparte de sí mismo y 1, por supuesto).

Matemáticamente no es necesario probar todos los números más bajos como posibles factores, solo primos inferiores hasta la raíz cuadrada de $ x. Esto se habilita almacenando primos tal como se encuentran en una matriz (que creo que es la estrategia a la que se refería el OP).

Tan pronto como se encuentre el primer factor primo, sabemos que $ x no es primo, por lo que no es necesario realizar más pruebas de ese valor de $ x y podemos salir del ciclo foreach.

$primes = array(); for ($x = 2; $x <= 1000; $x++) { $xIsPrime = TRUE; $sqrtX = sqrt($x); foreach ($primes as $prime) if ($prime > $sqrtX || ((!($x % $prime)) && (!$xIsPrime = FALSE))) break; if ($xIsPrime) echo ($primes[] = $x) . "<br>"; }



Sé que esto llegará un poco tarde, pero espero que ayude a alguien.

function prime_number_finder($range) { $total_count=0;//intitialize the range keeper $i=1;//initialize the numbers to check while ($total_count<=$range) { $count=0;//initialize prime number inner count $k=$i; while ($k!=0) { if(($i%$k)==0) { $count++; } $k--; } //condition to check if a number is prime if($count==2 || $count==1) { echo $i."</br>";//output the prime number; $total_count++; $i++; } //number is not prime if($count>2) { //$total_count++; $i++; } } }

// ejemplo prime_number_finder (200);


Cualquier cosa que sea sqrt () es falsa o cualquier valor flotante es número primo


$n = 7; if ($n == 1) { echo ''Not a Prime or Composite No.''; } $set = 0; for ($index = 2; $index <= $n/2; $index++) { if ($n % $index === 0) { $set = 1; break; } } if ($set) { echo ''Composite''; } else { echo ''Prime''; }


Sieve_of_Eratosthenes es un algoritmo simple y más rápido para encontrar números primos.

function getPrimes($finish) { $number = 2; $range = range($number,$finish); $primes = array_combine($range,$range); while($number*$number < $finish){ for($i=$number; $i<=$finish; $i+=$number){ if($i==$number){ continue; } unset($primes[$i]); } $number = next($primes); } return $primes; }


Esta es una implementación básica:

function prima($n){ for($i=1;$i<=$n;$i++){ //numbers to be checked as prime $counter = 0; for($j=1;$j<=$i;$j++){ //all divisible factors if($i % $j==0){ $counter++; } } //prime requires 2 rules ( divisible by 1 and divisible by itself) if($counter==2){ print $i." is Prime <br/>"; } } } prima(20); //find prime numbers from 1-20

Esto producirá

2 is Prime 3 is Prime 5 is Prime 7 is Prime 11 is Prime 13 is Prime 17 is Prime 19 is Prime

Complete la lógica paso a paso y la analogía visual aquí: aquí


Encuentre los números primos entre 1 y 10000, usando un cierre en array_filter ():

$start = 2; $step = 10000; $stop = $start + $step; $candidates = range($start, $stop); for($num = 2; $num <= sqrt($stop); ++$num){ $candidates = array_filter($candidates, function ($v) use (&$num){ return ($v % $num) != 0 || $v == $num ; } ); } print_r($candidates);

Editar: 1 no es un número primo


La mejor manera de verificar si un número es primo es ver si es divisible por cualquier número primo antes de él. Pi (x) es el que sigo viendo en todas partes ... Puedes ver un poco más de información sobre Prime Counting en wikipedia .

Entonces la forma más eficiente en que puedo pensar en este momento es la siguiente:

class prime { public $primes = [ 2, 3, 5, 7 ]; public $not_prime = [ 1, 4, 6, 8, 9 ]; public function is_prime( int $n ) { if ( $n <= 1 ) return false; if ( in_array( $n, $this->primes ) ) return true; if ( in_array( $n, $this->not_prime ) ) return false; for( $i = 0; $i < count( array_slice( $this->primes, 0, $this->prime_count( $n ) ) ) || $i == $n; $i++ ) { if ( $n % $this->primes[ $i ] == 0 ) return false; } return true; } public function build_primes_to( int $n ) { for ( $i = end( $this->primes ) + 1; $i <= $n; $i++ ) { if ( $this->is_prime( $i ) ) { $this->primes[] = $i; } else { $this->not_prime[] = $i; } } } public function prime_count( $n ) { $ln = log( $n ); if ( $ln == 0 ) return 1; return intval( ceil( $n / $ln ) ); } }

Lo cual no es realmente muy eficiente, bueno, no cuando se trata de construir la lista de números primos ... He estado trabajando en una mejor forma de construir la lista aquí , aunque sería igual de fácil y mucho más eficiente. para encontrar una lista en línea y usar eso.

El uso de lo anterior sería a lo largo de las líneas de:

$find_to = 1000; $prime = new prime(); $prime->build_primes_to( $find_to ); print "<pre>"; for ( $i = 1; $i < $find_to; $i++ ) { print "$i is " . ( !$prime->is_prime( $i ) ? "not " : "" ) . "prime/n"; }


Lo sé demasiado tarde, pero encontré que esta solución es mucho mejor y más fácil

function isPrime($num) { if ($num < 2) { return false; } for ($i = 2; $i <= $num / 2; $i++) { if ($num % $i == 0) { return false; } } return true; }


Aquí hay una pequeña función que encontré: ( http://icdif.com/computing/2011/09/15/check-number-prime-number/ ) ¡Parecía funcionar para mí!

function isPrime($num) { //1 is not prime. See: http://en.wikipedia.org/wiki/Prime_number#Primality_of_one if($num == 1) return false; //2 is prime (the only even number that is prime) if($num == 2) return true; /** * if the number is divisible by two, then it''s not prime and it''s no longer * needed to check other even numbers */ if($num % 2 == 0) { return false; } /** * Checks the odd numbers. If any of them is a factor, then it returns false. * The sqrt can be an aproximation, hence just for the sake of * security, one rounds it to the next highest integer value. */ $ceil = ceil(sqrt($num)); for($i = 3; $i <= $ceil; $i = $i + 2) { if($num % $i == 0) return false; } return true; }


Sé que esto llega un poco tarde, pero aquí hay un programa simple para ayudarte a hacer justo lo que estás pidiendo ...

<?php //Prime Function function fn_prime($number) { $i = 2; $result = TRUE; while($i < $number) { if(!($number%$i)) { $result = FALSE; } $i++; } return $result; } //Declare integer variable... $k = 0; //Start Loop up to any number of your choice for e.g. 200 while($k < 200) { if(fn_prime($k)) { echo "$k is a prime number<br/>"; } else { echo "$k is not a prime number!<br/>"; } $k++; } ?>


Versión mejorada de la respuesta @Farkie hecha especialmente para verificar primos en bucles.

function isPrime_v2($num) { static $knownPrimes=[3]; // array to save known primes if($num == 1) return false; if($num == 2 || $num == 3) //added ''3'' return true; if($num % 2 == 0) return false; $ceil = ceil(sqrt($num)); //same purpose, good point from Farkie // Check against known primes to shorten operations // There is no sense to check agains numbers in between foreach($knownPrimesas $prime){ if ($prime>$ceil) break; if($num===$prime) return true; if($num % $prime == 0) return false; } /** * end($knownPrimes) % 2 !==0 - mathematically guaranteed * start with latest known prime */ for($i = end($knownPrimes)+2; $i <= $ceil; $i = $i + 2) { if($num % $i == 0) return false; } $knownPrimes[]=$num; return true; }

Benchmark con phpfiddle.org. V1 - Respuesta de Farkie, V2 - Versión mejorada

V1 (1 to 5,000,000): divisions=330 929 171; primes=348 513; time=21.243s V2 (1 to 5,000,000): divisions=114 291 299; primes=348 513; time=10.357s

¡NOTA! isPrime_v2 función isPrime_v2 es aplicable SÓLO en caso de bucle desde 3. De lo contrario, la matriz $ knownPrimes guardada tendrá un historial insuficiente.


<?php function prime_number($num){ for( $j = 2; $j <= $num; $j++ ) { for( $k = 2; $k < $j; $k++ ) { if( $j % $k == 0 ) { break; } } if( $k == $j ) echo "Prime Number : ".$j."<br>"; } } prime_number(23); ?>


Aquí hay un trazador de líneas que encontré hace un tiempo para verificar los números primos. Utiliza marcas de conteo (matemáticas unarias) para determinar:

function is_prime_via_preg_expanded($number) { return !preg_match(''/^1?$|^(11+?)/1+$/x'', str_repeat(''1'', $number)); }

Verifique todos los números secuencialmente para primos:

$i=2; // start here (2 is the first prime) while (1) { // neverending loop if (is_prime_via_preg_expanded($i)) echo $i." <br />/n"; $i++; }

Para verificar solo un rango de números para números primos como en el ejemplo proporcionado:

$start = 2; // start here (2 is the first prime) $end = 100; $i=$start; while ($i<=$end) { if (is_prime_via_preg_expanded($i)) echo $i." <br />/n"; $i++; }


Aquí hay otro enfoque muy simple pero silencioso y efectivo:

function primes($n){ $prime = range(2 , $n); foreach ($prime as $key => $value) { for ($i=2; $i < $value ; $i++) { if (is_int($value / $i)) { unset($prime[$key]); break; } } } foreach ($prime as $value) { echo $value.''<br>''; } } primes(1000);