6677

Primes In C

Dec 24th, 2014
212
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.42 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. int main(void) {//declare a method called main. This method returns an int. This method takes no parameters (void).
  4.     int i;
  5.     for (i = 0; i < 100; i++) {//these last 2 lines effectively combine as for (int i = 0; i < 100; i++)  however some compilers reject that and prefer i to be declared seperately
  6.         if (isPrime(i) > 0) { //isPrime returns 1 if the number is a prime number, 0 if it is not a prime number. 1 is greater than 0 so this statement will be executed if i is prime
  7.             printf("%d\n",i);//print the number to the console
  8.         }
  9.     }
  10.     return 0;//this method was declared as returning an int. Here we return that integer, in this case 0.
  11. }
  12.  
  13.  
  14. int isPrime(int x) {//declare a method called isPrime. This method returns an int. This method takes an int as a parameter and within the method the parameter will be known as x
  15.     int flag = 0;//create a flag
  16.    
  17.     int i;
  18.     for (i = 2; i <= (x / 2); i++) {//loop from 2 to half of the input number
  19.         if ((x%i) == 0) {//if the input number can be divisible by i, the flag will be changed to 1. Importantly we never ever set the flag back to 0.
  20.             flag = 1;
  21.         }
  22.     }
  23.    
  24.     if (flag == 0) {//if the flag was never changed to 1, then it is still 0 indicating that our number cannot be divisible by any value smaller than itself
  25.         return 1;//we therefore return 1 to show that this number is a prime number
  26.     }
  27.     else {
  28.         return 0;//or we return 0 if it isnt a prime number
  29.     }
  30. }
Advertisement
Add Comment
Please, Sign In to add comment