algorithm - 在不使用 * 运算符且不使用按位的情况下将两个数字相乘,时间复杂度小于 O(N)

标签 algorithm

我需要一种算法来将两个数字相乘,而不使用乘法 (*) 运算符,并且不使用复杂度小于 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) - log(4))。总和中的 log (n) 总数为 O(log(n))。从这个最终解决方案的复杂性来看,O(log^2(n))。

关于algorithm - 在不使用 * 运算符且不使用按位的情况下将两个数字相乘,时间复杂度小于 O(N),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33547713/

相关文章:

算法面试题

algorithm - 请解释杂音散列?

java - 以下语法正确吗?

algorithm - 借助堆栈确定该单词来自语言

algorithm - 连续背包与连续背包0-1 背包

algorithm - 从 n 个数字的总和中找到最接近的 n

algorithm - 在大图中搜索简单图

algorithm - 使用 Bubble Up 的冒泡排序

algorithm - 解析器解析搜索词并提取有值(value)的信息

c - C程序中出现 "Abnormal Program Termination"错误的可能原因是什么?