Monday 5 January 2015

Finding factor


Question:
a) Find the factors of a number using "for" loop. Find the factors of 200.
b) Find the factors of a number using "while" loop. Find the factors of 200.
c) Write a function using any of the two loops. Find the factors of 200.

Answer: I have commented the code so that everyone will be able to understand the code. Please do feel to contact me if you have a doubt or if you have found a mistake in the program. Please do contact me if you think that you have a good program than this, so that it can be shared here.
a) 

n = 200#Initialize number 200 as variable
for i in range(2,n):#Looping through the number 
 if n%i == 0:#Check whether a number is dividing or not
  print "Factor has been found",i #Print if the factor is found

Output:

Factor has been found 2
Factor has been found 4
Factor has been found 5
Factor has been found 8
Factor has been found 10
Factor has been found 20
Factor has been found 25
Factor has been found 40
Factor has been found 50
Factor has been found 100

b) 

n = 200#Initialize number 200 as variable
i = 2 #For while loop initialization
while i<n:#Looping through the numbers greater than 2 and less than n
        if n%i == 0:#Check whether a number is dividing or not
                print "Factor has been found",i #Print if the factor is found
        i += 1
Output:

Factor has been found 2
Factor has been found 4
Factor has been found 5
Factor has been found 8
Factor has been found 10
Factor has been found 20
Factor has been found 25
Factor has been found 40
Factor has been found 50
Factor has been found 100
c)  I will use for loop for my function. You can use anything of your choice. If you use while loop you will have to replace the for loop code with the while loop code as it is. As simple as that. :)


def factors(n):#Function definition
        i = 2 #For while loop initialization
        while i<n:#Looping through the numbers greater than 2 and less than n
                if n%i == 0:#Check whether a number is dividing or not
                        print "Factor has been found",i #Print if the factor is found
                i += 1

factors(200)#Function Call
Output:


Factor has been found 2
Factor has been found 4
Factor has been found 5
Factor has been found 8
Factor has been found 10
Factor has been found 20
Factor has been found 25
Factor has been found 40
Factor has been found 50
Factor has been found 100

Find the code and compile it directly without the python interpreter on your personal computer, here: mycode
Note: This is my own code and is not copied.

No comments:

Post a Comment