Search This Blog

2025/05/10

Revisiting Algorithm -- Multiplication of decimal number using matrix

Here we revisit the our algorithm to multiplyy two decimal number.

I will try to rewrite the aalgorithm as i feel previous attempt may
be successfull yet it does not appeal my senses.

Here is my new attempt,the code is in python.I am not proficient in python so
some common coding practices might be misssing,if anyone find some please let
me know in comments.

Along with intellectual honesty politeness is also virtue that let you grow in choosen
field so keep comments if any short & precise & upto point.  

Code:
        from collections import defaultdict
        import math

        decimalMultiplicand: int = 378
        decimalMultiplier: int = 250

        def decimalToArray(n):
            return [int(digit) for digit in str(n)]

        def getMultiplication(multiplicand: int, multiplier: int):
            try:
                multiplicandArray = decimalToArray(decimalMultiplicand) #378
                multiplierArray = decimalToArray(multiplier) #24

                i = len(multiplicandArray) -1
                j =  len(multiplierArray) -1
               
                k =0
                intervalSize = len(multiplicandArray)
                sum =0
                power=0

                while j >=0:
                    while i >=0:
                        intermediateResult = multiplierArray[j] * multiplicandArray[i]
                        formattedNumber = f"{intermediateResult:02}"
                        sum = sum + (intermediateResult * (10 **(power+k)))
                        i=i-1
                        k=k+1
                    i=len(multiplicandArray) -1
                    k=0
                    power =power+1
                    j=j-1
                       
                multiplication = multiplicand * multiplier
                return sum
            except Exception as e:
                print(f"An error occured:{e}")
                raise

        result =getMultiplication(decimalMultiplicand, decimalMultiplier)
        print(f"Result:{decimalMultiplicand} * {decimalMultiplier}={result}")


No comments:

Post a Comment