Write the following in C:
2. An integer is said to be prime if it is divisible by only 1 and itself. Write a function called prime() that takes in one integer number, and returns 1 (true) if the number is prime and 0 (false) otherwise. Write a program to generate six random numbers between 1 to 100 and calls function prime() on each one to determine if it is prime or not.
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <math.h> int isPrime(int num) { int i; if (num <= 1) return 0; if (num % 2 == 0 && num > 2) return 0; for (i = 3; i <= sqrt(num); i += 2) { if (num % i == 0) return 0; } return 1; } int main() { int n, i; srand(time(NULL)); for(i = 0;i<6;i++){ n = 1+rand()%100; if(isPrime(n)){ printf("%d is prime\n",n); } else{ printf("%d is not prime\n",n); } } return 0; }
Get Answers For Free
Most questions answered within 1 hours.