192k views
2 votes
Exercise 4: Write a C function that takes a positive integer n as an argument and returns 1 if n is prime, and 0 otherwise.

User Shutefan
by
8.6k points

1 Answer

3 votes

Final answer:

The C function 'isPrime' determines if a number is prime by checking divisibility with numbers up to its square root. The function returns 1 if the number is prime and returns 0 otherwise.

Step-by-step explanation:

The task is to write a C function that checks whether a given positive integer n is prime. To achieve this, the function should iterate through all numbers from 2 to the square root of n, since if n is divisible by any number less than or equal to its square root, it is not prime. If n is found to be divisible by any such number, the function should return 0, indicating that n is not prime. If no divisors are found, the function should return 1, confirming that n is indeed a prime number. Here is an example of how such a function can be implemented:

int isPrime(int n)

This function covers several cases: the non-prime numbers 0 and 1, an optimization check for multiples of 2 and 3, and a loop that decreases the number of iterations needed by checking up to the square root of n.

User Litanhua
by
8.3k points