我正在尝试为今晚到期的项目的一部分掌握 Big O 的想法,我不知道我是否正确地考虑了这一点......
该项目包括我们为数学运算编写迭代和递归解决方案。
这里有一些方法。
public int inc(int n)
{
n = n + 1;
return n;
}
public int dec(int n)
{
n = n - 1;
return n;
}
public int add(int lhs, int rhs)
{
int sum = lhs;
while (rhs > 0) {
sum = inc(sum);
rhs = dec(rhs);
} // while
return sum;
}
public int fac(int num)
{
int ans = num;
while(num > 1)
{
ans = mul(ans, dec(num));
}
return ans;
}
public int div(int lhs, int rhs) throws ArithmeticException
{
int quot = 0;
while (lhs > 0)
{
lhs = sub(lhs,rhs);
if(lhs < rhs)
{
quot = 0;
}
else
{
quot = inc(quot);
}
}
return quot;
}
public int lshift(int lhs, int rhs)
{
return mul(lhs,pow(2,rhs));
}
所有这些都是 O(n) 吗?还是只是 inc、dec 和 add?
对于调用其他方法的行(如 mul - multiply - 在 fac 和 lshift 中),这是恒定时间还是再次 n,使得 O(n^2)?有人可以解释一下吗?
我将如何处理递归方法?
public int mul(int lhs, int rhs)
{
if (rhs == 0 || lhs == 0) return 0;
else if(rhs == 1) return lhs;
return add(lhs, mul(lhs, dec(rhs)));
}
除非有人要求其他人,否则我将仅保留 1 个递归示例。if 和 else if 分别被认为是常数时间,对吗?然后返回调用各种其他递归方法,以及它本身(显然),我真的不知道从哪里开始。
有人可以尝试简单地解释一下吗?
编辑:添加战俘
public int pow(int lhs, int rhs)
{
int ans = lhs;
for(int i = rhs; i > 1; i--)
{
ans = mul(ans,lhs);
}
return ans;
}