这个算法的时间复杂度是多少?

时间:2016-08-15 03:05:03

标签: algorithm time-complexity number-theory

编写一个带整数的程序,并打印出所有方法来乘以等于原始数字的较小整数,而不重复多组因子。换句话说,如果您的输出包含4 * 3,则不应再次打印3 * 4,因为这将是重复集。请注意,这不是仅要求素数分解。此外,您可以假设输入整数的大小合理;正确性比效率更重要。 PrintFactors(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)。这是因为递归深度将达到素因子的数量。但它并不紧张。有什么建议吗?

3 个答案:

答案 0 :(得分:3)

2个想法:

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

另外,根据师父定理,等式为:F(N) = d * F(N/2) + O(N),所以我们总体上O(N^log_2(d))

答案 1 :(得分:1)

时间复杂度应为:

number of iterations * number of sub calls ^ depth

由于the number of divisors of N is O(log N)

,有O(log N)次调用而不是O(N)

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

答案 2 :(得分:0)

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))
相关问题