Home > Software engineering >  How to multiple number given number of times without any module or methods
How to multiple number given number of times without any module or methods

Time:12-17

I am trying to implement this but got stuck

num = 10
r = 3

Need to multiple num 3 times as r is 3

Output : 10 * 10 * 10 -> 1000

Should not be using pow or **

CodePudding user response:

If you don't want to use pow, you can implement a pow by yourself. Generally, you should have a loop to repeat multiple to count of your r:

num = 10
r = 3

result = 1
counter = 0
while counter < r:
    result = result * num
    counter  = 1

CodePudding user response:

You can use while loop to perform power calculation.

Working:-

Initialising res=1 because the minimum value of result can be 1 i.e when r=0

In every iteration res is multiply by the num and the value of r is decreased by 1 this loop will iterate till the r becomes 0.

Now you can print the res as you achieved the power calculation..

Note:-

limitation. if the power is negative this code not work. it works when 0<=r<= inf

num = 10
r = 3
res=1
while r:
    res=num*res
    r-=1
print(res) #1000

if the constraints are -inf<=r=< inf:

you can apply this code..!

num = 10
r = -3
res=1
if r>=0:
    while r:
        res=num*res
        r-=1
    print(res) 
else:
    while r<0:
        res=res/num
        r =1
    print(res)

CodePudding user response:

Use a loop to repeat the multiplication

def my_pow(value, power):
    result = 1
    for _ in range(power):
        result *= value
    return result

print(my_pow(2, 4))  # 16
print(my_pow(10, 3))  # 1000
  • Related