81.2k views
4 votes
14) Modify the method that calculates the sum of the integers between 1 and N. Have the new version match the following recursive definition: The sum of 1 to N is the sum of 1 to (N/2) plus the sum of (N/2 1) to N. Trace your solution using an N of 7.

User Wazime
by
7.2k points

1 Answer

3 votes

Step-by-step explanation:

Let solve the program using Java programming language

Method: method means group of statements to perform some operation.

let call the method sum.

Parameters: list of variables that are use in the method for declaration.

The code

public int sum (int number)

int answer;

if (number == 1)

answer = number;

else

{

int half = number/2;

int span = number - half;

answer = sum(half) + sum(span) + (half * span);

}

answer result;

}

Firstly we defined the method called sum(), the method takes only one parameter which is number and return the answer(sum of the integers 1 and N).

if the number is equal to 1, so it will return the number and if the number is not equal to 1 it will divide the number by 2 and get the span(span used to shift upper range).And result will add sum of half, sum of span and product of half span.

User Inquiryqueue
by
8.2k points

No related questions found