Write a C program that prompts the user to input as many uns

Write a C program that prompts the user to input as many unsigned(n) as the user wants to type, terminated by non negative number

You may assume without checking that when the user is supposed to type an unsigned, he nevertypes a double

You may assume without checking that when the user is supposed to type an unsigned, he nevertypes a negative number.

For each number the user types, output whether that number is prime or not.

You won\'t need a die function for this program, but you will need a prime function:

int prime(unsigned n);

prime does no I/O. It\'s job is to return whether n is prime (1 or 0).

If you know a correct algorithm for determining whether n is prime, feel free to use it. Or, you\'re free to use the following algorithm:

if n is less than 4, then we\'re done: it\'s prime if it\'s greater than 1

if n is even, then we\'re done: it\'s not prime

for fac taking on the values 3, 5, 7, 9, ...

if fac is greater than n/fac, we\'re done: n is prime  

if n is divisible by fac, we\'re done: n is not prime

Solution


// C code
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <assert.h>
#include <string.h>
#include <ctype.h>
#include <inttypes.h>
#include <stdbool.h>
#include <unistd.h>

int prime (unsigned int n)
{
     if (n <= 1) return 0;
     if (n % 2 == 0 && n > 2) return 0;
     for(int i = 3; i < n / 2; i+= 2)
     {
         if (n % i == 0)
             return 0;
     }
     return 1;
}

int main()
{
    unsigned int n;

    while(1)
    {
        printf(\"Enter n: \");
        scanf(\"%u\",&n);

        if(n == 0)
            break;

        else
        {
            if(prime(n) == 1)
                printf(\"%d is prime\ \ \",n);
            else
                printf(\"%d is not prime\ \ \",n);
        }
    }

    return 0;
}

/*
output;

Enter n: 12
12 is not prime

Enter n: 22
22 is not prime

Enter n: 23
23 is prime

Enter n: 0

*/

Write a C program that prompts the user to input as many unsigned(n) as the user wants to type, terminated by non negative number You may assume without checkin
Write a C program that prompts the user to input as many unsigned(n) as the user wants to type, terminated by non negative number You may assume without checkin

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site