13

Compute prime numbers

  1. #include <math.h>
  2.  
  3. int isprime(int n) {
  4.     double sn;
  5.     int d;
  6.  
  7.     if (n < 2)
  8.         return 0;
  9.     if (n == 2)
  10.         return 1;
  11.     if (n % 2 == 0)
  12.         return 0;
  13.  
  14.     sn = sqrt(n);
  15.  
  16.     for (d = 3; d <= sn; d += 2)
  17.         if (n % d == 0)
  18.             return 0;
  19.     return 1;
  20. }
  21.  
  22. #include <stdio.h>
  23.  
  24. int main() {
  25.     int n;
  26.  
  27.     for (n = 1; n < 100; n++)
  28.         if (isprime(n) )
  29.             printf("%d ", n);
  30.     printf("\n");
  31. }
$ gcc -o prime prime.c -lm
$ ./prime
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 

Comments

Your comment:
[p] [b] [i] [u] [s] [quote] [pre] [br] [code] [url] [email] strip help 2000

Enter a maximum of 2000 characters.
Improve the presentation of your text with the following formatting tags:
[p]paragraph[/p], [b]bold[/b], [i]italics[/i], [u]underline[/u], [s]strike[/s], [quote]citation[/quote], [pre]as is[/pre], [br]line break,
[url]http://www.izend.org[/url], [url=http://www.izend.org]site[/url], [email]izend@izend.org[/email], [email=izend@izend.org]izend[/email],
[code]command[/code], [code=language]source code in c, java, php, html, javascript, xml, css, sql, bash, dos, make, etc.[/code].