使用链表的快速GCF算法

时间:2016-09-25 14:06:53

标签: algorithm linked-list greatest-common-divisor

我使用2个链表来表示2个非常长的整数,每个数字占用一个节点。我需要快速计算他们的gcf但我当前的算法计算很长时间。请帮助我改进它/或者如果你可以为链表建议其他更快的算法。

这是我目前的代码:

int findGCD(number **larger, number **small, number **gcdtop){
    number *a = *larger, *b = *small, *aptr, *bptr; 
    printlist(larger);
    printlist(small);
    int equal = checkEqual(a, b); //traverse through linked list a & b and compare if equal, returns 1 if true
    int large=0, borrow=0, adata=0, bdata=0, i=0;
    while(equal!=1){
        equal = checkEqual(a, b);
        if(equal==1) break;
        flip(&a);  //Flips the linked list
        flip(&b);
        large = whatGreater(&a, &b); //Checks which linkedlist is greater
        flip(&a); //Flip it back
        flip(&b);
borrow=0;
//Do repeated subtraction (Euclid's algorithm)
        if(large==1){ 
            aptr =  a;
            bptr = b;
            while(a && b){
                adata   = a->data;
                bdata = b->data;
                adata = adata - borrow;
                if(adata>=bdata){
                    a->data = (adata-bdata);
                    borrow=0;
                } 
                else if(adata<bdata){
                    adata = adata+10;
                    a->data = (adata-bdata);
                borrow = 1;
                }
                a = a->next;
                b = b->next;
            }
            a = aptr;
            b = bptr;
        }
        else if(large==0){
            aptr = a;
            bptr = b;
            while(a && b){
                adata   = a->data;
                bdata = b->data;
                bdata = bdata - borrow;
                if(bdata>=adata){
                    b->data = (bdata-adata);
                    borrow=0;
                } 
                else if(bdata<adata){
                    bdata = bdata+10;
                    b->data = (bdata-adata);
                    borrow = 1;
                }
                a = a->next;
                b = b->next;
            }
            a = aptr;
            b = bptr;   
        }
    }

我相信做这个除法/模数会更快但我无法在链表中实现它。

以下是输入样本:15424832369192002264032565635067237193339888184999832384884463019917546384661904,65227

提前谢谢。

0 个答案:

没有答案