# Is this a good solution strategy?

• 07-31-2009, 07:07 AM
hedonist
Is this a good solution strategy?
Write a program SumMain, that includes a recursive method computing the sum of the integers 1, 2, 3, …, N. The computation should be based on the following principle: the sum of the integers from 1 to N is equal to the sum of the integers from 1 to N/2 added with the sum of the integers from N/2+1 to N. Is this a good solution strategy?

This is what i have done: I want opinions on the last part of the question, "Is this a good solution strategy?"

Thanks.

import java.io.*;

public class SumMain {

static int input;
static int sum = 0;
static int val;
static int first;
static int second;

public static void main(String args[])
{
try
{
System.out.print("Enter a number: ");

first = 1;
second = input/2;

val = calculate(first,second)+calculate(second+1,input);
System.out.println(val);
}
catch(Exception e)
System.out.println(e);

}

public static int calculate(int num, int n)
{
if(n==num)
return num;
else
{
return(n+calculate(num,n-1));
}

}
}
• 07-31-2009, 08:18 AM
mtyoung
in method calculate, you did not use the recursive function the question requested.
sum of the integers from 1 to N/2 added with the sum of the integers from N/2+1
not sum of n and 1 to N-1

for problem like sum of AP, you only need to simply apply the general equation of sum of AP is enough.
Divide and conquer strategy is good, but not for too simple problems
• 07-31-2009, 08:30 PM
hedonist
Let me see....
Thanks