-->

Print the even and odd numbers of a Magic series generated up to N numbers

 Print the even and odd numbers of a Magic series generated up to N numbers

   This Problem asked in HirePro Coding Question.

Write a program to print the even and odd numbers of a Magic series generated up to N numbers, when the first two numbers A and N are given.

The magic series is a series of numbers in which each number is the sum of the two preceding numbers.

Read the input from STDIN and print the output to STDOUT.Do not write arbitrary strings while reading the input or while printing, as these contribute to the standard output.

Constraints:

1<N<10

Input Format:

The first line of input contains two space-separated integers A and B

The second line of input contains N

Outut Format:

The first line of output contains even numbers from the series in an ascending order,

where the numbers are seperated by a single white space.

The second line of output contains odd numbers from the series in an ascending order,

where the numbers are seperated by a single white space.

Sample Input 1:

2 3

10

Sample Output 1:

2 8 34 144

3 5 13 21 55 89

Sample Input 2:

23 32

8

Sample Output 2:

32 142 600 

23 55 87 229 371

Solution:
import java.util.Scanner;
/**
 * Main
 */
public class Main {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        int A = s.nextInt();
        int B = s.nextInt();
        int N = s.nextInt();
        s.close();
        printMagicNumber(N, A, B);
    }

    private static void printMagicNumber(int N, int A, int B) {
        int[] arr = new int[N];
        arr[0] = A;
        arr[1] = B;

        for (int i = 2; i < N; i++) {
            arr[i] = arr[i - 1] + arr[i - 2];
        }
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] % 2 == 0)
                System.out.print(arr[i] + " ");
        }
        System.out.println("");
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] % 2 != 0)
                System.out.print(arr[i] + " ");
        }
    }
}

Post a Comment

0 Comments