Ohad Aloni - CV (Résumé)

Find the 2 Primes that add up to a given even number


3 + 617 = 620

<?php
/*------------------------------------------------------------*/
class Primes extends Mcontroller {
    
/*------------------------------------------------------------*/
    
public function index() {
        
$n = @$_REQUEST['n'];
        if ( ! 
$n )
            
$n rand(2,500) * 2;
        
$this->Mview->msg("Find the 2 Primes that add up to a given even number\n\n");
        
$this->Mview->showTpl("stringInput.tpl", array(
            
'name' => "n",
            
'value' => $n,
            
'submitTitle' => "Go",
            
'hidden' => array(
                
'class' => "Primes",
            ),
        ));
        if ( ! 
is_numeric($n) ) {
            
$this->Mview->error("$n is not numeric");
            return;
        }
        
$n round($n);
        if ( 
$n <= ) {
            
$this->Mview->error("$n must be greater than 2");
            return;
        }
        if ( 
$n != ) {
            
$this->Mview->error("$n must be an even number");
            return;
        }
        
$primes $this->primesTill($n);

        
$numPrimes count($primes);
        for(
$i=0;$i<$numPrimes;$i++) {
            for (
$j=$i;$j<$numPrimes;$j++) {
                
$sum $primes[$i] + $primes[$j] ;
                if ( 
$sum == $n ) {
                    
$this->Mview->msg("{$primes[$i]} + {$primes[$j]} = $n");
                    return;
                }
            }
        }
        
$this->Mview->error("Oops: failed to find the answer for $n");

    }
    
/*------------------------------------------------------------*/
    /*------------------------------------------------------------*/
    
private function primesTill($n) {
        
$primes = array();
        for(
$i=2$i $n;$i++) {
            if ( 
$this->isPrime($i$primes) )
                
$primes[] = $i;
        }
        return(
$primes);
    }
    
/*------------------------------------------------------------*/
    
private function isPrime($n$primes) {
        foreach( 
$primes as $prime )
            if ( 
$n $prime == )
                return(
false);
        return(
true);
    }
    
/*------------------------------------------------------------*/
}
/*------------------------------------------------------------*/
Running Time: 5.212 milliseconds


All the source code on this site is in the public domain
© Ohad Aloni 2018