c - 我的 LCM 程序的复杂性是多少?

标签 c algorithm complexity-theory

下面给出的是一个求可变数量数字的最小公倍数的程序。

例如:如果我必须找到 3,9,13 的 lcm 那么它执行如下: 长厘米(1,3) 长厘米(3,9) lcm(9,13)

我只想知道这个程序的复杂性是多少。是 O(n) 还是 O(n^2)。你能告诉我为什么会这样吗?

#include <stdio.h>

int gcd(int x,int y)
{
    int n;
    if(x>y)
        n=y;
    else
        n=x;

    while(n>=0){
        if(x%n==0 && y%n==0){
            return n;
            break;
        }
        n--;
}
    return 1;
}

int lcm(int a,int b)
{
    return a*b/gcd(a,b);
}

int main()
{
    int tot,i,l=1;
    int n[10];
    printf("Enter the total numbers:");
    scanf("%d",&tot);
    if(tot>10 || tot<2){
        printf("Sorry invalid inputs");
        return 1;
    }

    printf("Enter the numbers one by one:");
    for(i=0;i<tot;i++)
        scanf("%d",&n[i]);

    for(i=0;i<tot;i++){
        l=lcm(l,n[i]);
    }

    printf("The LCM is %d",l);
    return 0;


}

最佳答案

gcd 方法的复杂度(也是 lcm 方法的复杂度)为 O(n),其中 n 为 max(x, y)。这是因为在最坏的情况下 x 和 y 互质,这意味着 n 必须递减到 1。Euclid 的 GCD 算法更快:http://en.wikipedia.org/wiki/Euclidean_algorithm

关于c - 我的 LCM 程序的复杂性是多少?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23577867/

相关文章:

c - 字符串复制函数

转换为 void**,出于什么原因?

c - 将指向 char 数组的指针初始化为可变指针的最佳方法是什么?

algorithm - 非常长的整数的乘法

algorithm - 为什么 O(1) != O(log(n)) ?对于 n=[整数, 长, ...]

在不使用结构作为链表的情况下创建 map

java - Floyd warshall 实现似乎缺少最短路径

c++ - 递归搜索 n 叉树中的元素

java - 最坏情况分析循环

c - 这个代码片段的时间复杂度是O(n)吗?