0

so i'm trying to write code under the following specs - enter a decimal number containing up to 3 numbers and decides if the number entered is a prime number. If more than 3 numbers are entered, program should output the message More than 3 characters and exit. If a non-numeric character is entered, the program should output the message Invalid input and exit. If the input is valid, your program should display either the message number entered is a prime number or the message number entered is not a prime number.

i'm really unsure not just how to calculate a prime number using loops but also where to input that into my program. I understand this is quite a basic question.

#include <stdio.h>
#include <string.h>
#define FALSE 0
#define TRUE 1
/* check string only contains decimal digits */
int numeric(char* string)
{
    int i, valid;
    valid = TRUE;
    for (i = 0; i < strlen(string); i++)
    {
        if (string[i] < '0' || string[i] > '9')
            valid = FALSE;
    }
    return valid;
}
/* main function */
int main()
{
    char number[4];
    int count, toolong = FALSE;
    printf("Enter number: ");
    fgets(number, 4, stdin);
    
    if (number[strlen(number) - 1] == '\n')
        number[strlen(number) - 1] = '\0';

    else
        
        while (getchar() != '\n')
            toolong = TRUE;
    if (toolong)
    {
        printf("More than 3 characters");
        return 1;
    }
    
    if (!numeric(number))
    {
        printf("'%s' is an invalid number\n",
            number);
    }

        printf("'%s' is a valid number\n",
            number);
    
    
    return 0;
}

Thank you :)

1 Answers1

1

i'm really unsure not just how to calculate a prime number using loops

The simplest way is to use Trial division. You check if the number you're checking is divisible by 2. Then you check if it's divisible by 3. On and on until you reach the square root of the number you're checking. See here for how to check if one number is divisible by another.

Wikipedia notes that this isn't a very efficient method, but for the small numbers you're checking, it doesn't matter.

also where to input that into my program

After you decide that a number is a valid number, and you parse the string into an int, you should check if the number is prime.

Nick ODell
  • 15,465
  • 3
  • 32
  • 66