Can someone help me out with this simple C program?! Thank you! Write a complete
ID: 3681002 • Letter: C
Question
Can someone help me out with this simple C program?! Thank you!
Write a complete program, called primality_testing.c, which tests whether a given number is prime. An integer is a prime number if it is greater than 1 and can only be divided evenly by 1 and by itself. Write a program to test whether a user provided positive integer k is a prime number or not, and, if it isn’t, provide a counter-example (a number, other than 1 and k that divides k).
For example, when theuser enters 37, the output should be:
37 is prime.
When user enters 24, the output should be:
24 is not prime because it is divisible by 2.
(Hint. You can use a while loop and an if statement to solve this question. An if statement will be needed to check whether k can be evenly divided by an integer. You may also find it helpful to declare a variable to keep track whether a factor of k has been found. Initialize this variable to be 0 and update it to 1 when a factor of k is found. Then you can check the value of this variable to decide whether k is a prime or not)
Explanation / Answer
#include<stdio.h>
int main()
{
int k,i,f;
printf("Enter a number: ");
scanf("%d",&k);
f=0;
i=2;
while(i <= k/2)
{
if(k%i == 0)
{
f=1;
break;
}
i++;
}
if(f==0)
{
printf("%d",k);
printf(" is prime.");
}
else
{
printf("%d",k);
printf(" is not prime because it is divisible by 2.");
}
return 0;
}
OutPut:
Enter a number: 5 5 is prime.
Enter a number: 6 6 is not prime because it is divisible by 2.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.