Factors of a number using python
This exercise is to find all the factors of a given number. Remember that a factor divides evenly into a number without leaving a remainder. We can use the modulo operator (%) to check for any remainder. The program will check all integers from 2 up to but not including the original number. To loop through those numbers we will use the for
loop combined with the range()
function.
number = int(input("Enter the number?")) for i in range(2,number): remainder = number % i quotient = number // i print(number,"=",i,"x",quotient,"+ remainder",remainder) if remainder == 0: print("remainder is zero so",i,"is a factor") else: print("remainder is not zero so",i,"is not a factor")
Using print()
in this way shows clearly the flow of the program. However, two lines of code for each potential factor is a lot to read through. To reduce the number of lines of code, print()
lets us specify a different ending than a new line. If we specify end=’ ‘ then print() will end the line with a space rather than a new line significantly reducing the number of lines of output.
The following program ignores output when the number is not a factor, and displays all the factors on the same line, with a final message whether the original number is prime or composite. Instead of asking for the number to be entered, the program finds all factors for all numbers between 2 and 99 inclusive.
for number in range(2,100): print(number,'factors:', end=' ') prime=True for i in range(2,number): if number%i == 0: print(i, end=' ') prime=False if prime: print('prime') else: print('composite')