A composite number is a number that has factors. (It's the opposite of a prime number.)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
|
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.
- Oops!
©2017 Graham Mitchell