Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Create the isPrime function following these requirements: Input: an unsigned int

ID: 3831730 • Letter: C

Question

Create the isPrime function following these requirements:

Input: an unsigned integer value.

Output: true if the value sent in is prime, and false if it is not prime.

Side effects: None.

Let limit be the integer (truncated) square root of the value sent in.

If the number sent in is 0 or 1, the result should be false.

If the number sent in is 2, the result should be true.

If the number sent in is divisible by 2, the result should be false.

If none of the above conditions has been met, assume the number sent in is prime (result is true) and set up a loop to prove otherwise. The loop should run from 3 through limit, incrementing by 2. On each iteration, check to see if the number sent in is divisible by the loop counter. If it is, then the result is false and you should end the loop and return.

Return the result.

Explanation / Answer

bool isPrime (unsigned int n)
{
int k = 2;
unsigned int limit = sqrt(n);
if (n == 0 || n == 1) return false;
if (n == 2) return true;
if(n % 2 == 0) return false;
unsigned int i;
for(i = 3; i <= limit; i += 2)
{
if(n % i == 0)
return false;
}
return true;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote