بخشی از مجموعه

چندین نمونه کد

~2 دقیقه مطالعه • بروزرسانی ۲۵ شهریور ۱۴۰۴

Program Overview

This Python program reads two positive integers m and n from the user.
It calculates m to the power of n using only repeated addition, without using multiplication or exponentiation operators.
This approach is useful for understanding algorithmic logic and low-level computation.


Python Code:


def multiply(a, b):
    result = 0
    for _ in range(b):
        result += a
    return result

def power(m, n):
    result = 1
    for _ in range(n):
        result = multiply(result, m)
    return result

m = int(input("Enter m (positive integer): "))
n = int(input("Enter n (positive integer): "))

if m > 0 and n >= 0:
    result = power(m, n)
    print(f"{m} to the power of {n} is:", result)
else:
    print("Please enter only positive integers.")

Sample Output:


Enter m (positive integer): 3
Enter n (positive integer): 4
3 to the power of 4 is: 81

Explanation:

Here’s how the program works:
- The multiply() function simulates multiplication using repeated addition
- The power() function uses repeated multiplication to compute exponentiation
- No use of *, **, or pow() is made
- Input validation ensures both numbers are positive integers


نوشته و پژوهش شده توسط دکتر شاهین صیامی