繁体   English   中英

该算法的时间复杂度是多少

[英]What is the time complexity of this algorithm

编写一个使用整数的程序,并打印出所有方法以将等于原始数的较小整数相乘,而无需重复因子集。 换句话说,如果您的输出包含4 * 3,则不应再次打印3 * 4,因为这将是重复集。 请注意,这并非仅要求素因数分解。 同样,您可以假定输入整数的大小是合理的。 正确比效率更重要。 打印因子(12)12 * 1 6 * 2 4 * 3 3 * 2 * 2

public void printFactors(int number) {
    printFactors("", number, number);
}

public void printFactors(String expression, int dividend, int previous) {
    if(expression == "")
        System.out.println(previous + " * 1");

    for (int factor = dividend - 1; factor >= 2; --factor) {
        if (dividend % factor == 0 && factor <= previous) {
            int next = dividend / factor;
            if (next <= factor)
                if (next <= previous)
                    System.out.println(expression + factor + " * " + next);

            printFactors(expression + factor + " * ", next, factor);
        }
    }
}

我认为是这样

如果给定数为N,素数为N = d,则时间复杂度为O(N ^ d)。 这是因为递归深度将达到素数的数量。 但这不是束缚。 有什么建议么?

2个想法:

该算法对输出敏感。 输出因式分解最多用完循环的O(N)次迭代,因此总体上我们有O(N * number_of_factorizations)个

同样,通过大师定理,该等式为: F(N) = d * F(N/2) + O(N) ,所以总体而言,我们有O(N^log_2(d))

时间复杂度应为:

number of iterations * number of sub calls ^ depth

因为O 的除数为O(log N) ,所以有O(log N)个子调用而不是O(N)

递归深度也为O(log N),每个递归调用的迭代次数小于N /(2 ^ depth),因此总时间复杂度为O(N((log N)/ 2)^(log N))

The time complexity is calculated as : Total number of iterations multiplied 
by no of sub iterations^depth.So over all complexity id Y(n)=O(no of
dividends)*O(number of factorization )+O(no of (factors-2) in loop);

Example PrintFactors(12) 12 * 1 ,6 * 2, 4 * 3, 3 * 2 * 2
O(no of dividends)=12
O(number of factorization)=3
O(no of factors-2){ in case of 3 * 2 * 2)=1 extra

Over all: O(N^logbase2(dividends))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM