Skip to content

Instantly share code, notes, and snippets.

@duythinht
Created March 6, 2015 17:40
Show Gist options
  • Save duythinht/ad48b722dbe1290e1ec1 to your computer and use it in GitHub Desktop.
Save duythinht/ad48b722dbe1290e1ec1 to your computer and use it in GitHub Desktop.
<?php
//This code read the necessary data form the standard input
function isPrime($n) {
if ($n == 1) return false;
if($n == 2) return true;
if ($n % 2 == 0) return false;
for($i = 3; $i <= ceil(sqrt($n)); $i = $i + 2) {
if($n % $i == 0) return false;
}
return true;
}
while ($line = trim(fgets(STDIN))) {
//$line contains the line of the input
//echo $line . "\n";
$current_num = 2; // Start find prime begin as 2
$sum = 0; // set default result
$counter = 0; // set counter = 0, its increament when a prime number has been sum
while ($counter <= intval($line)) {
if(isPrime($current_num)) $sum = $sum + $current_num;
}
echo $sum . "\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment