开发者

writing a function that takes int n and returns the sum of odd less than n

Here is my code

public static int sumOfOddLessThan(int n)
{
    int iResult = 0;
    for(int i = n - 1;开发者_高级运维 i > 0 && i % 2 != 0; i--)
    {
        iResult = iResult + i;
    }
    return iResult;
}

It does not work correctly, I dunno why :\

It should return 4 when I enter 5 but it returns 0


Your conditional in the for loop reads:

i is greater than 0 and i is not even.

When you call the method with 5 as argument, the first value of i will be 4, which is even and therefore the loop does not get evaluated.

for(i = n-1; i > 0; i++) {
    if(i%2==0) {
        iResult += i;
    }
}


You're putting the condition i % 2 != 0 in the for loop instead of an if inside of the loop, hence if it's not met even once it breaks out of the entire loop.

Your code should look like this:

public static int sumOfOddLessThan(int n)
{
    int iResult = 0;
    for(int i = n - 1; i > 0; i--)
    {
        if(i % 2 != 0) {
            iResult = iResult + i;
        }
    }
    return iResult;
}

Then again you don't even need a loop, you can evaluate it directly by getting the number of odd numbers lower than N and squaring that.


you should modify the forumla used for adding the series, all you gotta do is to modify it

earlier

int i = (n+1)/2;
return (i*i)

modified

int i = n/2;
return (i*i);

TEST input 1: return 0;

input 2: return 1;

input 3: return 1;

input 4: return 4;

input 5: return 4;

input 6: return 9;

and so on ..


The second part of a for loop is a continuation condition. In your case, your continuation condition is i > 0 && i % 2 != 0.

For n = 5, the first i is 4, and 4 % 2 is 0. Your continuation condition is not met, and this is why your for loop exits before it begins.

Try

    for(int i = n - 1; i > 0; i--)
    {
        if (i % 2 != 0)
        {
            iResult = iResult + i;
        }
    }


The problem is that when the condition in the for is false, the loop exits.

So for 5, i=4 and i % 2 != 0 is false, so the loop isn't accessed at all.

Try this instead:

for(i=((n-1)%2==0?n-2:n-1 ; i>0; i=i-2)
{   
     i > 0 && i % 2 != 0; 
}

Note that by reducing 2 from i at each step, you don't have to check parity on every loop.


First you are setting i as n-1, so it would be 4 if n is 5, then your condition on the for loop states that i must be odd, which 4 is not, so it doesn't even do one loop. Try this:

public static int sumOfOddLessThan(int n)
{
    int iResult = 0;
    for(int i = n-1; i > 0; i--)
    {
        if (i % 2 != 0) iResult += i;
    }
    return iResult;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜