Is Composite Function

A composite number is a number that has factors. (It's the opposite of a prime number.)

iscomposite.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
from __future__ import print_function
input = raw_input

def isComposite(n):
    if n < 3:
        return True
    for f in range(2,n):
        if n%f == 0:
            return True
    return False

def test(n):
    print("isComposite({}) => {}".format(n, isComposite(n)))

def main():
    test(2)
    test(11)
    test(20)
    test(1337)
    num = int(input("Enter a number: "))
    print(isComposite(num))

main()

What You Should See

isComposite(2) => True
isComposite(11) => False
isComposite(20) => True
isComposite(1337) => True
Enter a number: 2017
False

Remember that % means modulus. It divides a two numbers and tells you the remainder. If a factor f goes into a number n with nothing left over, then n is divisible by f. For example, 20%10 == 0 because 10 goes into 20 exactly twice with no remainder.

In Python, the range function generates a list of numbers. range(2,n) gives you all the numbers from 2 up to (but not including n).

range(4,10) produces 4,5,6,7,8,9
range(1,5) produces 1,2,3,4

So if we find a factor that goes into n evenly, then n is composite.

Study Drills

  1. Oops!



©2017 Graham Mitchell