Odd’s and Even’s using..

Write a method to print all odd and even numbers of a given number.

Again this can done using

for loop and
recursions

package solutions.java;

/**
 * Created by rchouhan on 10/30/14.
 */
public class OddAndEvenNumbers {

    public static void main(String[] args){
        System.out.println("\nPrinting all odd numbers for the given input using for loop: "+ getOddSequenceUsingFor(100));
        System.out.println("\nPrinting all even numbers for the given input using for loop: "+ getEvenSequenceUsingFor(100));
        System.out.println("\nPrinting all odd numbers for the given input using recursion: "+ getOddSequenceUsingRecursion(100));
        System.out.println("\nPrinting all even numbers for the given input using recursion: "+ getEvenSequenceUsingRecursion(100));
    }

    // Using FOR loop

    // Time Complexity is O(n) - linear
    private static String getOddSequenceUsingFor(int input){
        String oddValues = "";
        for(int i=1; i<= input; i +=2){
            oddValues += i + ",";
        }
        return oddValues;
    }

    // Time Complexity is O(n) - linear
    private static String getEvenSequenceUsingFor(int input){
        String evenValues = "";
        for(int i=0; i<= input; i +=2){
            evenValues += i + ",";
        }
        return evenValues;
    }


    // Using Recursion

    // Time Complexity is O(n) - linear
    private static String oddValues = "";
    private static int i =1;
    private static String getOddSequenceUsingRecursion(int input){
        if(input < i){
            return oddValues;
        }
        oddValues += i + ",";
        i +=2;

        return getOddSequenceUsingRecursion(input);
    }

    // Time Complexity is O(n) - linear
    private static String evenValues = "";
    private static int e =0;
    private static String getEvenSequenceUsingRecursion(int input){
        if(input < e){
            return evenValues;
        }
        evenValues += e + ",";
        e +=2;

        return getEvenSequenceUsingRecursion(input);
    }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s