[Solved] Math Olympiad with Java

The KISA Math Olympiad is held annually across all the Schools to identify and encourage the mathematical creativity of children of all grades. Samuel is a little genius in math of Grade 5 who was participating in the contest.

The question bank of the contest contains 35 questions and lasts for duration of 1 hour. Samuel was so confident of all the questions but he was seemed stuck at one question. He needs your help in answering that question so that he could score full marks and get a Gold medal in the event. The question that needs your assistance is as follows:

Write a recursive method to find the m-th summation of first n natural numbers. m-th summation of first n natural numbers is defined as following.
If m > 1
SUM(n, m) = SUM(SUM(n, m – 1), 1)
Else
SUM(n, 1) = Sum of first n natural numbers.
We are given m and n, we need to find SUM(n, m).

Hence create a class named FindSum with the following method.

Method NameDescription
int summation(int,int)                                             This recursive method should return the m-th summation of first n natural numbers.

Create a driver class called Main. In the Main method, obtain input from the user in the console and display the m-th summation of first n natural numbers by calling the summation method present in the FindSum class.

[Note: Strictly adhere to the Object Oriented Specifications given in the problem statement.

All class names, attribute names and method names should be the same as specified in the problem statement.]
Input Format:
First line of the input is an integer ‘n’.
Second line of the input is an integer ‘m’.

Output Format:
Output in a single line an integer that gives the m-th summation of first n natural numbers.
Refer sample input and output for formatting specifications.

Sample Input 1:
5
3

Sample Output 1:
7260

Sample Input 2:
4
2

Sample Output 2:
55

Solution

import java.util.*;
public class Main
{
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int m = sc.nextInt();
        int result = summation(n,m);
        System.out.println(result);
    }
    
    public static int summation (int n,int m)
    {
        if(m > 1)
        return summation(summation(n,m-1),1);
        return (int)(n*(n+1)*0.5);
    }
}

Happy Learning – If you require any further information, feel free to contact me.

Share your love
Saurav Hathi

Saurav Hathi

I'm currently studying Bachelor of Computer Science at Lovely Professional University in Punjab.

📌 Nodejs and Android 😎
📌 Java

Articles: 444

Leave a Reply

Your email address will not be published. Required fields are marked *