spot the problem

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
It's missing a return for the else clause.
Since you say it has no defined purpose, there are no other errors.
ty for answering : )

he said there`s/are problem/(s) in this code that we need to solve it in 2 diff way .
The assignment is moronic.
hahaha u get me man XD
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
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
int ludicrous( int n ) { return 1 + ( n == 2 || n >= 4 ) * ( n - 1 - 3 * ( n % 2 == 1 )); }
Nice one. I couldn't figure out how to remove the conditionals.

You can remove the == 1 and a set of parens if you wish.

 
int ludicrous2( int n ) { return 1 + ( n == 2 || n >= 4 ) * ( n - 1 - n % 2 * 3 ); }

That's even better (in a deliberate obfuscation sort of way!)
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
Topic archived. No new replies allowed.