programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# How to store only odd numbers

Dana Ucaed
Ranch Hand
Posts: 406
6
I want to find all odd numbers between two numbers.

For example: [3, 9] all odd numbers are: 3, 5, 7, 9.

I created a solution but I don't know how to compute number of odd numbers between 2 numbers.

Probably, sure there is a formula to calculate number of odd numbers.

}

Thanks,

Ryan McGuire
Ranch Hand
Posts: 1143
9
I see one issue at line 26.  What index of odd1 are you assigning to each time?  Try working through an example by hand and see if that's what you wanted.

Bigger picture... It would really help us help you if you say what behavior you're seeing now.  Do you get any output?  If so, what?  Are any exceptions being thrown?

As for calculating the count of odd numbers in a range...
It seems to me that the count of odds is approximately equal to the size of the range divided by 2.  The actual result will within 1 of that result.  For instance, the count of odd numbers between 50 and 75 is probably within 1 of 25/2 - 12 or 13.  The detail of whether to add something to the range size divided by 2 is related to whether the high and low numbers are even or odd.

What can you put in those "other columns" so that you arrive at the result in the final column?

Dana Ucaed
Ranch Hand
Posts: 406
6
My code is OK, but I don't want to display 0, if the number is even.

I found a formula for odd numbers and I want to create a new array only for odd numbers.

I get the exception and is normal:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at oddnumbers.OddNumbers.oddNumbers1(OddNumbers.java:55)
at oddnumbers.OddNumbers.main(OddNumbers.java:70)
BUILD FAILED (total time: 0 seconds)

But how can resolve this exception?

Ryan McGuire
Ranch Hand
Posts: 1143
9
Look at the same line of code as before, which has now moved to line 17.  What index values are you using for odd1?

EDIT: More detail...
Let's say l=3 and r=9.
What is the size of temp[]?
What is the size of odd1[]?
What values will i have in the for loop?

Dana Ucaed
Ranch Hand
Posts: 406
6

Look at a second version.

[3,7]

temp.length = 5;

[3,4, 5, 6,7]

odd1.length = 3.
[3, 5, 7]

Dana Ucaed
Ranch Hand
Posts: 406
6
I resolved: int j = 0; and j++ and it is OK.

Thanks.

Campbell Ritchie
Marshal
Posts: 56541
172
Sounds like a job for IntStreamMan!

See if you can't get a much more elegant solution with an IntStream.

 Don't get me started about those stupid light bulbs.