sasori Posted April 3, 2012 Share Posted April 3, 2012 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? Quote Link to comment Share on other sites More sharing options...
dragon_sa Posted April 3, 2012 Share Posted April 3, 2012 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); ?> Quote Link to comment Share on other sites More sharing options...
Psycho Posted April 3, 2012 Share Posted April 3, 2012 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. Quote Link to comment Share on other sites More sharing options...
Psycho Posted April 3, 2012 Share Posted April 3, 2012 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); Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.