Introduction:
This code example demonstrates how to find the factors of a given number using a while loop in Python. By entering a number, the program will display all the factors of that number.
Code:
#Find the factors of a number using while loop
num = int(input("Enter a number to find its factor: "))
print (1, end=' ') #1 is a factor of every number
factor = 2
while factor <= num/2 :
if num % factor == 0:
#the optional parameter end of print function specifies the delimeter
#blank space(' ') to print next value on same line
print(factor, end=' ')
factor += 1
print (num, end=' ') #every number is a factor of itself
Logic:
- Accept a number from the user as input.
- Initialize the factor variable to 2.
- While the factor is less than or equal to half of the number:
a. Check if the number is divisible by the factor using the modulo operator.
b. If the number is divisible, print the factor.
c. Increment the factor by 1. - Print the number itself as a factor.
Output:
The program will display all the factors of the entered number. The factors will be printed on a single line, separated by a blank space.
>> 1 2 3 4 6 12