logoISU  

CS256 - Principles of Structured Design

Fall 2021

Displaying ./code/cs256su21code/midtermSol/p3.c

/*

3. Write a function named isPrime that takes in a single integer,and returns 1 if the number is prime, and 
   0 if it isn't. If the user enters a 1 or less, have the function return 0
   
   Hint: Recall that Prime Numbers are numbers that have only 2 factors: 1 and themselves. I 
   suggest using a loop going from 2 to (but not including) n and check each number if n % i == 0
   (assuming we're using i as the counting variable). If that statement is true, then we know that
   n isn't prime, so we can go ahead and return 0. If the loop is allowed to completely finish, then 
   we were unable to find a number that divides n, so the number must be prime. If that happens, we 
   return 1.


*/

#include <stdio.h>

int isPrime(int n);

int main(){

   int num;
   printf("Check if this number is prime: ");
   scanf("%d", &num);

   if(isPrime(num) == 1)
      printf("%d is Prime\n", num);
   else
      printf("%d is NOT Prime\n", num);

   return 0;

}

int isPrime(int n){

   if(n <= 1) return 0;

   for(int i = 2; i < n; i++){
      if(n % i == 0)
         return 0;
   }

   return 1;
}