How to find Biggest Prime Number with PHP

For beginners.

Write a program that finds and prints the biggest prime number which is <= N

This is optimized script only for the bigger Prime Numeber

Sample tests

Input Output
13 13
126 113
26 23

Example:

<?php
$num = trim(fgets(STDIN));
settype($num, "int");
if ($num <= 10000000){
    for($i= $num; $i>=3; $i--) {
        $isPrime = true;
        for($j = 2; $j <= sqrt($i); $j++) {
            if($i % $j == 0) {
                $isPrime = false;
            }
        }
        if($isPrime) {
            echo $i;
            break;
        }
    }
}

Beginner task level

This is the way to find Prime Num but is not optimized to find the biggest:

<?php
//the input
$input = fgets(STDIN);
settype($input, "int"); //we find diggits

//the function
function prima($n){
    $max_num = 0;

    for($i=1;$i<=$n;$i++){

        $counter = 0;
        for($j=1;$j<=$i;$j++){
            if($i % $j==0){
                $counter++;
            }
        }
        if($counter==2){
            if ($i > $max_num) {
                $max_num = $i;
            }
        }
    }
    return $max_num;
}
//call the function with value
if ($input <= 10000000){
    echo prima($input);
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll Up