I'm trying to grasp the idea of Big O for part of a project that is due tonight and I don't know if i'm thinking this through right or not...
The project included us writing Iterative and Recursive solutions to math operations.
Here are some of the methods.
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));
}
Would all these be O(n)? Or just inc,dec, and add?
For lines where other methods are called (like mul - multiply - in fac and lshift), is this constant time or is it n again, making O(n^2)? Could someone explain?
And how would I go about dealing with recursive methods?
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)));
}
I'll just leave it with 1 recursive example unless anyone asks for others. The if and else if be considered constant time each, correct? Then the return is calling all sorts of other recursive methods, as well as itself (obviously), and I really have no clue where to start.
Could someone try to explain this really simply?
EDIT: Added Pow
public int pow(int lhs, int rhs)
{
int ans = lhs;
for(int i = rhs; i > 1; i--)
{
ans = mul(ans,lhs);
}
return ans;
}