# Odd and Even Numbers

• September 30th, 2012, 03:52 PM
tyb97
[SOLVED] Odd and Even Numbers
I am trying to create an "algorithm" (what I have now really isn't), I just can't seem to wrap my head around the concept, or on how to do this.. Here is the monstrosity I have created so far:

Code :

```package org.buchanan.math;   import java.util.ArrayList; import java.util.List;   public class Numbers {   private List<Integer> oddNumbers = new ArrayList<Integer>(); private List<Integer> evenNumbers = new ArrayList<Integer>();   public void populateLists() { for (int j = 0; j < Integer.MAX_VALUE; j += 1) { this.oddNumbers.add(j); System.out.println(j); } System.out.println("Odd numbers added!"); for (int i = 0; i < Integer.MAX_VALUE; i += 2) { this.evenNumbers.add(i); } System.out.println("Even numbers added!"); }   public boolean isOddNumber(int n) { return this.oddNumbers.contains(n) ? true : false; }   public boolean isEvenNumber(int n) { return this.evenNumbers.contains(n) ? true : false; } }```

As you see, this destroys my memory, is slow as all get out, and not efficient in any way. Anybody have any suggestions on how to make this? Maybe even somewhere easier to start learning things like this?
• September 30th, 2012, 04:02 PM
helloworld922
Re: Odd and Even Numbers
Try using the Modulo operator. It will save you a lot of time and memory.
• September 30th, 2012, 04:11 PM
tyb97
Re: Odd and Even Numbers
Quote:

Originally Posted by helloworld922
Try using the Modulo operator. It will save you a lot of time and memory.

Ahh, thanks a ton. I still don't fully understand them, but in time I will. I was able to reduce my code from the above to this:

Code :

```package org.buchanan.math;   public class Numbers {   public boolean isOddNumber(int n) { return n % 2 != 0 ? true : false; }   public boolean isEvenNumber(int n) { return n % 2 == 0 ? true : false; } }```

Which really helps a ton, and save a lot of memory.
• September 30th, 2012, 04:16 PM
Norm
Re: Odd and Even Numbers
Quote:

return n % 2 != 0 ? true : false;
You could return the results of the != directly and not need to use the ternary statement.
return n % 2 != 0;
• September 30th, 2012, 04:19 PM
tyb97
Re: Odd and Even Numbers
Quote:

Originally Posted by Norm
You could return the results of the != directly and not need to use the ternary statement.
return n % 2 != 0;

I see. Thank you for the kind insight.