@ nitin1:
i have calculates the time complexity as O(nlogn). Am i right ? please verify.
If n denotes the number of your numbers, I'd say it's O(n). The method described here (which looks like what you were trying to do) also has an asymptotic time complexity of O(n). I used the term complexity in a broader sense in my previous post. Let's take a deeper look at what happens in both approaches. Note that even if operating on the list argument is an option, the second method still has to make a copy, because the algorithm needs both lists.
@ WaltP:
Unless you can prove to me recursion uses fewer resources than non-recursion.
The term you're looking for is iteration. And I don't have to prove anything. What you said is a fact.
Consider this:
#include <stdio.h>
inline int gcdRec(int a, int b) { return b == 0 ? a : gcdRec(b, a % b); }
inline int gcdLoop(int a, int b)
{
while (b != 0)
{
int temp = a % b;
a = b;
b = temp;
}
return a;
}
int main()
{
printf("%d\n", gcdRec (12, 18));
printf("%d\n", gcdLoop(12, 18));
return 0;
}
This is what my compiler generated for the gcdRec and gcdLoop functions, respectively:
[...]
movl $12, %eax
movl $18, %ecx
jmp L17
.p2align 2,,3
L19:
movl %ecx, %eax
movl %edx, %ecx
L17:
cltd
idivl %ecx
testl %edx, %edx
jne L19
[...] …