Reputation: 107
I need to complete a method which is passed an int(max) as a parameter and returns the sum of the odd integers from 1 to max (inclusive).
For example, sumOfOddIntegers(5)
must return 9. i.e. 1 + 3 + 5 = 9
My attempt was this:
int sumOfOddIntegers(int max) {
int sumOdd = 0;
int digit;
while (max >= 1) {
digit = max%10;
if (digit%2 == 1)
sumOdd += digit;
max /= 10;
}
return sumOdd;
}
But it does not work with some inputs such as 5, 9, etc. What do I need to change in my code?
Upvotes: 1
Views: 7577
Reputation: 62466
To make the sum of odd integers from 1
to max
, you can use the Java 8 Stream
s
public static int sumOddIntegers(int max){
if(max<1) return 0;
return IntStream.rangeClosed(1, max).filter(i -> i%2 != 0).sum();
}
The following method calls are used:
IntStream.rangeClosed(1, max)
to generate a stream of int
from 1 to max
.
filter(i->i%2!=0)
to keep only odd int
sum()
to make the sum.
You then find the right values.
Upvotes: 0
Reputation: 497
If you are trying to get s sum of odd number, you are not required to do digit = max%10; or max/= 10;
See the comments in your code, let say max = 98
/****FIRST RUN****/
// digit = 98%10 = 8
digit = max%10;
// 8 % 2 == 0
if( digit % 2 == 1 )
sumOdd += digit;
// max = 98/10 = 9
max/= 10;
/****SECOND RUN****/
// digit = 9%10 = 9
digit = max%10;
// 9 % 2 == 1
if( digit % 2 == 1 )
// sumOdd = 1
sumOdd += digit;
// max = 9/10 = 0
max/= 10;
Your output is 1, which is not what you expect. Hence, in order to compute sum of odd number you can proceed via:
for(int i = 1; i <= max; i+= 2)
{
oddSum += i; // assuming oddSum = 0, and max is > 0
}
Upvotes: 4
Reputation: 21
Might be this helps :
import java.util.*;
class oddsum {
public static void main(String args[]) {
int sumOdd = 0;
int digit;
System.out.println("Please Enter Number.");
Scanner in = new Scanner(System.in);
int i = Integer.parseInt(in.nextLine());
int j;
for(j =1; j<=i; j+=2) {
sumOdd += j;
}
System.out.println(sumOdd);
}
}
Upvotes: 0
Reputation: 29166
Write a method that will take a number as input, and will check whether or not it's odd. If the number is odd, it may return true, otherwise it may return false (HINT: odd numbers aren't divisible by 2).
From your current method, loop from 1 to max
. Pass each number to this method to check if it's odd or not. If it is, add it to the sum.
Upvotes: 0
Reputation: 671
here is some code
void calculateOdd(int max) {
int total = 0;
for (int i=max; i>0; i--) {
if ( (i % 2) != 0 ) total+=i;
}
}
or
void calculateOdd(int max) {
int total = 0;
if ( (max % 2) == 0 ) max--;
for (int i=max; i>0; i--) {
total+=i;
i--;
}
}
Upvotes: 0
Reputation: 2242
why not just do this the easy way. Find the number of odd numbers in the range from 1 to max
and then square it. This might help you http://www.wikihow.com/Add-a-Sequence-of-Consecutive-Odd-Numbers
Upvotes: 10