Sum the number prime


/ Published in: PHP
Save to your folder(s)



Copy this code and paste it in your HTML
  1. <?php
  2.  
  3. define('N', 200);
  4.  
  5. function isPrime($num)
  6. {
  7. if ($num == 2 || $num == 3) { return 1; }
  8. if (!($num%2) || $num<1) { return 0; }
  9.  
  10. for ($n = 3; $n <= $num/2; $n += 2) {
  11. if (!($num%$n)) {
  12. return 0;
  13. }
  14. }
  15.  
  16. return 1;
  17. }
  18.  
  19. for ($i = 2; $i <= N; $i++) {
  20. if (isPrime($i)) {
  21. $sum += $i;
  22. }
  23. }
  24.  
  25. echo $sum;

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.