簡體   English   中英

不使用 * 運算符和不使用按位的時間復雜度小於 O(N) 的兩個數字相乘

[英]Multiplying two numbers without using * Operator and without using bitwise in Time Complexity less than O(N)

我需要一種算法來將兩個數字相乘,而不使用乘法 ( * ) 運算符,並且不使用復雜度小於 O(N) 的按位運算,我想出了最明顯的算法

int m = 6, n = 5, sum = 0;
for(int i = 0, i<n, i++)
    sum += m;

但這是 O(N) 對我不起作用。

我有以下解決方案

public static int mult(int m, int n) {
        int amount = 1;
        int bSum = 0;
        int sum = 0;
        int current = m;
        while (bSum + amount <= n) { 
            sum += current;
            current = current + current;
            bSum += amount;
            amount = amount + amount;
        }
        // bSum = 1+2+4+ ... + 2^k = 2^(k+1) - 1
        // cycle pass log(n) times

        if (bSum < n) {
            sum += mult(m, n - bSum); // n - bSum less n/2
        }
        return sum;
    }

復雜度為 O(log(n)+log(n/2)+log(n/4) + ...) = O(log(n)+log(n) - log(2) + log(n) - 日志(4))。 log (n) 的總數為 O(log(n))。 從解決方案的最終復雜性 O(log^2(n))。

謝謝你們,我想出了一個簡單的解決方案:

static ulong Mul(uint N, uint M)
    {   if (N == 0)
            return 0;
        if (N == 1)
            return M;
        ulong res;
        res = Mul(N / 2, M);
        if (N % 2 == 0)
            return res+res;
        else
            return res+res+M;
        }

這是 Python 中的遞歸解決方案:

import math
def fast_multiply(m, n):
    if n == 0: return 0
    shift_by = len("{0:b}".format(n)) - 1
    remainder = n - (1 << shift_by)
    return (m << shift_by) + fast_multiply(m, remainder)

這在 O(log(n)) 中運行,因為遞歸樹中最多有 log(n) 級,只有一個遞歸調用,並且 O(1) 在遞歸調用之外工作。

這是迭代,請參閱鏈接以進行解釋。

def multiply(x, y):
    if y < 0:
        return -multiply(x, -y)
    elif y == 0:
        return 0
    elif y == 1:
        return x
    else:
        return x + multiply(x, y - 1)

這里是一步一步解釋的鏈接,也是可視化 Python 代碼執行,你可以看到每一步,直到得到輸出

#include <bits/stdc++.h>
  
using namespace std;

int multiply(int a,int b)
{
  int temp;
  if( a == 0){

     return 0;

  }

  if( a == 1){

     return b;

   }

   temp = multiply(a/2, b);

   if (a % 2 == 0){

      return temp + temp;

   }

   else{

       return temp+temp+b;

     }
   }

 int main(){

 int a,b;

 cin>>a>>b;
 cout<<multiply(a,b)<<endl;

 return 0;
 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM