ByteBoard Notes Notes

Input a number and check whether it is a prime or a composite number

Computer Science XI · Experiment 12 of 27 · Python

★ CBSE suggested11-CSPython programs
Expt. No.12
Page No.24

Prime or composite

Aim

To write a Python program that checks whether a number is prime or composite.

Concepts used

Algorithm

  1. Input a number.
  2. If it is 1 or less, it is neither prime nor composite.
  3. Otherwise assume it is prime and try every divisor from 2 to number−1.
  4. If any divisor leaves remainder 0, it is composite; stop checking.
  5. Display the result.

Program

# Check whether a number is prime or composite num = int(input("Enter a number: "))if num <= 1:    print(num, "is neither prime nor composite")else:    is_prime = True    for i in range(2, num):        if num % i == 0:            is_prime = False            break    if is_prime:        print(num, "is a prime number")    else:        print(num, "is a composite number")

A marked line continues the line above it. In your file, write it on the same line.

Output

Run 1
$ python prime_or_composite.py
Enter a number: 29 29 is a prime number
Run 2
$ python prime_or_composite.py
Enter a number: 91 91 is a composite number
Run 3
$ python prime_or_composite.py
Enter a number: 1 1 is neither prime nor composite

✓ Printed by running this program, not typed by hand.

Result

29 was reported as prime, 91 as composite (it is 7 × 13, so the loop stopped at 7), and 1 as neither prime nor composite.

Viva voce: what the examiner may ask

01What does break do here?

It leaves the loop as soon as one divisor is found, because one is enough to prove the number is composite.

02Why is 1 neither prime nor composite?

A prime has exactly two divisors (1 and itself); 1 has only one divisor.

03How can the loop be made faster?

Check divisors only up to the square root of the number, since a larger divisor always pairs with a smaller one.

04What is a flag variable?

A variable like is_prime that records whether something happened inside a loop.

Variations for the lab test

  1. Print all prime numbers between 1 and 100.
  2. Count how many primes there are below 500.
  3. Stop the loop at int(num ** 0.5) + 1 and check the result is the same.
! Common mistake Printing "prime" inside the loop's else branch: the program would announce a result after testing only the first divisor.
Back to the 11-CS index