|
CS256 - Principles of Structured Design
Fall 2021
|
Displaying ./code/cs256su21code/jun29/isPrime.c
/*
revisiting isPrime, but using command line arguments to
run the program
if compiling on linux, you need to compile like this
>gcc isPrime.c -lm
or if you're naming your executable
>gcc -o isPrime isPrime.c -lm
either way, you will need to include the -lm if you are on linux,
this does not seem to be the case on macOS
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int isPrime(int n);
int main(int argc, char *argv[]){
// if the user enters too few arguments, it's good practice to print
// a usage statement, they're usually set up like this
if(argc < 2){
printf("Usage: %s <number>\n", argv[0]);
exit(-1); //similar to return, but exits the program entirely
// needs stdlib.h
}
int n = atoi(argv[1]); //atoi takes a number string and converts that to an integer
if(isPrime(n) == 1)
printf("%d is Prime\n", n);
else
printf("%d is NOT Prime\n", n);
return 0;
}
int isPrime(int n){
if(n <= 1) return 0;
//you can actually quit this loop at the square root of n
for(int i = 2; i < sqrt(n); i++){
if(n % i == 0)
return 0;
}
return 1;
}
|