Results 1 to 3 of 3
  1. #1
    hedonist is offline Member
    Join Date
    Jun 2009
    Posts
    35
    Rep Power
    0

    Default 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
    {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    System.out.print("Enter a number: ");
    input = Integer.parseInt(br.readLine());

    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));
    }

    }
    }

  2. #2
    mtyoung is offline Senior Member
    Join Date
    Dec 2008
    Location
    Hong Kong
    Posts
    473
    Rep Power
    6

    Default

    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

  3. #3
    hedonist is offline Member
    Join Date
    Jun 2009
    Posts
    35
    Rep Power
    0

Similar Threads

  1. Developing an Hex-board strategy game
    By abegade in forum Java 2D
    Replies: 8
    Last Post: 05-03-2011, 11:16 AM
  2. Hello Good Morning, Good afternoon, and Good Evening
    By MrFreeweed in forum Introductions
    Replies: 3
    Last Post: 12-11-2009, 03:32 PM
  3. Battery - Online Strategy-RPG
    By M77 in forum Reviews / Advertising
    Replies: 1
    Last Post: 11-16-2008, 09:21 PM
  4. Strategy Pattern
    By mew in forum New To Java
    Replies: 0
    Last Post: 01-25-2008, 07:34 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •