Saturday, 1 August 2020

Finding Sum of Odd factors of a number and print it.





 

Objective: 

To find the sum of odd factors of a number and print it

#Solution Code

def Odd_factors_Sum(n):
    factor_sum =
0
   
for i in range(1,int(n+1)):
       
if n % i == 0 and i % 2 == 1 :
            factor_sum = factor_sum + i
   
print("The sum of odd factors of the given number is: ", factor_sum)
"""End of Function"""
Reply = "Y"
while Reply == "Y" or Reply == "y":
    Number =
int(input("Enter the number whose sum of factors you want: "))
    Odd_factors_Sum(Number)
    Reply =
input("Press Y to continue or Press any other key to exit: ")

#Output




Explanation

Step 1:

We created a function Odd_factors_Sum() which takes a int as its parameter (here it takes n as formal parameter). In this function we declare a local variable named as factor_sum initialized as 0.

Step 2:

Then we run a for loop starting from i =0  to i = n and check “if n%i==0 and i%2 == 1”.This means we check if i divides n completely and also it leaves remainder 1 on division by 2 implying it is odd.

If both the conditions are true then we add number i to our variable storing the sum (factor_sum here).

Else we continue till i = n.

Step 3:

After the completion of this for loop we print the value of factor_sum.

Our function is completed.

Step 4:

Now in the driver code we declare a string type variable reply and initialize it with the value “Y and then we use a while loop.

Step 5: While Body

We check the condition if Reply == “Y” or Reply == “y”. Since this is true while bode is executed.

In while body we input the user entered number in a variable named “Number” and in the next line we call our function by reference as Odd_factors_Sum(Number).

Our result will be Printed.

Final Step:

We now input the value of “Reply” so that user can exit or continue the program.


Previous Post
Next Post