Skip to main content

Count prime and composite until -1

Short answer

Read numbers until -1. For each n>1, test primality by checking divisors up to sqrt(n); increment prime or composite accordingly. Ignore 0,1.

Write a program to read the number until -1 is encountered. Also count the number of prime number and composite numbers entered by the user.

Read numbers until -1. A prime number is greater than 1 and has no divisor other than 1 and itself; a composite number is greater than 1 and has other divisors. To test a number, check divisibility by 2, 3, ... up to √n (i * i <= n). The numbers 0 and 1 are neither prime nor composite, so they are not counted.

#include <stdio.h>
int main(void)
{
    int n, i, isprime, prime = 0, comp = 0;
    printf("Enter numbers (-1 to stop):\n");
    scanf("%d", &n);
    while (n != -1)
    {
        if (n > 1)
        {
            isprime = 1;
            for (i = 2; i * i <= n; i++)
                if (n % i == 0)
                {
                    isprime = 0;
                    break;
                }
            if (isprime) prime++;
            else comp++;
        }
        scanf("%d", &n);
    }
    printf("Prime numbers = %d\nComposite numbers = %d\n", prime, comp);
    return 0;
}

Output for the input 2, 9, 13, 1, 20, 7, -1:

Enter numbers (-1 to stop):
Prime numbers = 3
Composite numbers = 2

Primes: 2, 13, 7. Composite: 9, 20. The number 1 is neither.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Computer Programming chapter 5 questions →