Skip to content
Advertisement

How can I create an array of only “odd” numbers between 1 and n – Java?

I ran into an issue I can’t seem to solve, and all the searches I do are not completely relevant to the issue I am having, and trying to implement those things to solve my issue still doesn’t work. I’ve spent an hour trying to find another question or post somewhere that would help but can’t seem to find any specific to my issue (unless Google just doesn’t want to work today).

I am trying to create a method that returns an array of all of the odd numbers between 1 and n, say in this example 1 to 255. I tried the following (here is the method currently):

import java.util.Arrays;

public class BasicJava: { 
    public Integer[] arrayOfOdds() {
        
        int n = 255;
        Integer[] odds = new Integer[(n+1)/2];
        for(int i = 1; i < n+1; i+=2) {
            
            odds[i/2] = i;
        }
        
        return odds;
    }
}

Main Method:

import java.util.Arrays;

public class BasicJavaTest {
    public static void main(String[] args) {
        BasicJava test = new BasicJava();
        System.out.println(Arrays.toString(test.arrayOfOdds()));
    }

}

I tried using an array to do the same thing before switching to using an ArrayList (I like other data structures more than I do arrays) and converting to an array and got the same output (I will just put part of the output array to not use too much space):

[0, 1, 0, 3, 0, 5, 0, 7, 0, 9, 0, 11, 0, 13, 0, 15, 0, 17, 0, 19, 0, 21, 0, 23, 0, 25, 0, 27, 0, 29, 0, 31, 0]

What do I need to resolve this issue?

If I just wanted to print all of the odds between 1 and N using the same for loop and if statement, I would get the correct output.

Thank you

Advertisement

Answer

You can do this is linear time complexity and without using an ArrayList.

Your final output will always have n/2 elements so your array size can be fixed at the same. In the next step you can simply populate the values in your array.

FYR code:

int[] arr = new int[((n+1)/2)];
for(int i = 0, e = 1; i < arr.length; e += 2, i++) {
    arr[i] = e;
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement