Jul 14, 2020 at 11:21pm UTC
guys whats the problem with this code :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
int silly(int n)
{
if (n<=0)
{
return 1;
}
else if (n%2==0)
{
return n;
}
else
{
silly(n - 3);
}
}
apparently it has more than one problem [which i cant even spot one] [also there`s no specific purpose to it , its just a piece of code that they gave us]
Last edited on Jul 14, 2020 at 11:28pm UTC
Jul 14, 2020 at 11:37pm UTC
It's missing a return for the else clause.
Since you say it has no defined purpose, there are no other errors.
Jul 14, 2020 at 11:43pm UTC
ty for answering : )
he said there`s/are problem/(s) in this code that we need to solve it in 2 diff way .
Jul 14, 2020 at 11:45pm UTC
The assignment is moronic.
Jul 15, 2020 at 1:22am UTC
The function can also be re-written to avoid the recursion (
and be solved in constant time), by noting the fact that n is always odd in the else branch, and odd - odd = even.
[although recursion is not necessarily a problem]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
int silly2(int n)
{
if (n<=0)
{
return 1;
}
else if (n%2==0)
{
return n;
}
else if (n <= 3)
{
return 1;
}
else
{
return n - 3;
}
}
Edit: It's constant time (w.r.t. n) either way, so my comment is misleading..
Last edited on Jul 15, 2020 at 1:57am UTC
Jul 15, 2020 at 1:38am UTC
Good point. You could also use the conditional operator to create yet another version:
1 2 3 4 5 6 7
int idiotic(int n) {
return n <= 1 || n == 3
? 1
: n % 2 == 0
? n
: n - 3;
}
Last edited on Jul 15, 2020 at 1:38am UTC
Jul 15, 2020 at 2:43pm UTC
int ludicrous( int n ) { return 1 + ( n == 2 || n >= 4 ) * ( n - 1 - 3 * ( n % 2 == 1 )); }
Jul 15, 2020 at 3:41pm UTC
That's even better (in a deliberate obfuscation sort of way!)
Jul 17, 2020 at 9:16pm UTC
thank u so much guys : )
sorry i cdnt answer sooner since i didn't have access to internet
there is just one new prob i cant figure out the math behind them all XD
but thank u my main problem is solved