Jump to content

get prime numbers and print


sasori

Recommended Posts

hi , how to get the prime numbers of the positive integer input and print them?

 

here's what i have at the moment

function getPrime($num){
  if((int)$num == $num && (int)$num > 0){
    for($i = 2; $i < $num; $i++){
      for($j = 2; $j < $i; $j++){
        if($i % 2 == 1){
          echo $i.'<br />';
        }
      }
    }
  }
}

displayPrime(10);

 

the ouput should be

 

2,3,5,7

but the output apparently, is

 


3
5
5
5
7
7
7
7
7
9
9
9
9
9
9
9

 

how to solve this?

Link to comment
Share on other sites

hers a function that will work :)

 

<?php
function get_primes($number) {
    $primes = array(2);
    $x = 3;
    while($x < $number) {
        $isprime = true;
        foreach($primes as $val) {
            if($x % $val == 0) {
                $isprime = false;
            break;
            }
        }
        if($isprime) {
            $primes[] = $x;
        }
        $x+=2;
    }
    foreach($primes as $val) {
		echo $val."<br>";
    }
     
}
get_primes(20);
?>

Link to comment
Share on other sites

Yeah, that's not going to work. The only way I think would work would be to start at 2 and work your way up. Then for each number you need to test if it is divisible by any of the previous prime numbers. If not, then that number is prime and add it to your result. Then move to the next number up.

Link to comment
Share on other sites

Not sure about dragon_sa's solution, but I decided to give it a whack and came up with the following. I've tested it and confirmed it works. It returns an array of all the prime numbers up to and including the target number

function displayPrime($target)
{
    if((int)$target != $target || (int)$target < 2) { return false; }
    $primes = array(2);
    for($num = 3; $num <= $target; $num+=2)
    {
        $isprime = true;
        foreach($primes as $prime)
        {
            if($num % $prime == 0) { $isprime = false; break; }
        }
        if($isprime) { $primes[] = $num; }
    }
    return $primes;
}

$result = displayPrime(55);

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.