0

The sequence is: sum = 1 + 1/2 + 1/4 + 1/9 + 1/16 + 1/25+...

When I enter "2" it just gives me the sum of 1.25. How do you get it so when "2" is entered, it is adding 1 + 1/2?

Oh and I'm in an entry level java course so I we cant use arrays or anything that advance yet.

Thanks in advance!

import java.util.Scanner;
public class Sum
{
    public static void main(String[] args)
    {
        //declarations
        Scanner scan = new Scanner(System.in);
        double sum = 0;
        int n;

        //input
        System.out.println("Enter n: ");
        n = scan.nextInt();

        //process
        for(int counter = 1; counter <= n; counter += 1)
        {
            sum += 1.0 / (counter*counter);
        }

        System.out.println("The sum is: " + sum);
    }
}
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245

5 Answers5

0

The following code will solve your problem, i have used Math.pow() to get the sequence running and not multiplying it twice.

public static void main(String[] args) throws UnknownHostException {
        //declarations
        Scanner scan = new Scanner(System.in);
        //to generate this sequence we take the first two as constants and start generating from the third onwards
        double first = 1;//first number in the sequence
        double second = 0.5;//second number in the sequence
        double sum = first+second;//adding first and second
        int n;

        //input
        System.out.println("Enter n: ");
        n = scan.nextInt();
        if(n==1){
           System.out.println("The sum is: " + first);
           return;
        }
        if(n==2){
           System.out.println("The sum is: " + sum);
           return;
        }
        //process
        for(int counter = 2; counter <n; counter += 1)
        {
            sum += 1.0 / Math.pow(counter, 2);//will be computed when you enter values when n is more than 3

        }

        System.out.println("The sum is: " + sum);
     }
  • 1
    I think there's nothing wrong with OP's code. The problem is with the task definition. – Bohemian Oct 26 '16 at 23:55
  • You do NOT need to use `Math.pow`. And if the only power you'll be raising things is 2, it's far better to do it by multiplying. – Dawood ibn Kareem Oct 26 '16 at 23:58
  • If I enter "1" as "n", I get 1.5; which it is supposed to 1. Otherwise this is sooo close to getting it! – Koulae Moua Oct 27 '16 at 00:01
  • @KoulaeMoua fixed the code, it will work for all cases now – Shreyas Sarvothama Oct 27 '16 at 00:11
  • @Bohemian I feel with his code he can never generate first two numbers of the sequence, try it yourself.. correct me if i am wrong – Shreyas Sarvothama Oct 27 '16 at 00:11
  • @DavidWallace can you please tell me why multiplying two is better? – Shreyas Sarvothama Oct 27 '16 at 00:12
  • Multiplying two integers is better than calling `Math.pow()` because it is **much** faster. – Ted Hopp Oct 27 '16 at 01:27
  • It's not MUCH faster, but it's a little faster than a floating-point multiplication. `Math.pow` is implemented in the JVM. The implementation does a number of preliminary checks, to deal with common and easy-to-calculate cases. One of those checks is to check whether the exponent is 2, and if so, to get the result by performing a floating-point multiplication. These checks don't take terribly long, BUT, it's always going to be better just to save the JVM from having to do these checks, and code the floating-point multiplication directly. Of course, as @TedHopp correctly points out, ... – Dawood ibn Kareem Oct 27 '16 at 06:34
  • when you're dealing with integers, the multiplication is considerably faster. Integer operations at processor level will always be faster than the corresponding floating point operations. – Dawood ibn Kareem Oct 27 '16 at 06:37
  • As far as the downvote is concerned ... I downvoted your answer for two reasons. (1) It is false - you claim that OP _needs_ to use `Math.pow()`. This, of course, is nonsense. (2) It is not useful. It will not solve OP's problem. – Dawood ibn Kareem Oct 27 '16 at 06:39
  • @DavidWallace Thanks, I will change it now – Shreyas Sarvothama Oct 27 '16 at 06:54
  • @DavidWallace thanks for the elaborated explanation... learnt something new today – Shreyas Sarvothama Oct 27 '16 at 06:57
  • @DavidWallace - The comparison should be between one `int` multiply and subsequent promotion of `int` to `double` vs. the following: 1) promotion of `int` to `double`; 2) overhead of calling a two-argument `static` method; 3) check for special case; 4) `double` (not `float`) multiplication. I stand by my statement that the `int` multiply is MUCH faster. According to [this study](http://dhruba.name/2012/09/01/performance-pattern-multiplication-is-20x-faster-than-math-pow/), `double` (not `int`!) multiply can be up to **20x faster** than calling `Math.pow()`. – Ted Hopp Oct 27 '16 at 14:54
  • @TedHopp That study's results aren't really applicable here. It deals with the general case, where the exponent is any positive integer. The Hotspot JVMs have some special logic for the case where the exponent is exactly 2. Intuitively, the `Math.pow` implementation looks like `if (exponent == 2.0) { return base * base; } else { do clever stuff }`. If you compare the performance of `Math.pow(x,2)` with `x*x`, you'll find the difference is actually very small. However, that's no excuse to use the former. – Dawood ibn Kareem Oct 28 '16 at 04:07
  • @DavidWallace - Yes, the study I cited may not be the most relevant. However, we're still talking here about a 32-bit `int` multiply vs. a 64-bit `double` multiply (not `Math.pow(x,2)` vs. `x*x`). The [Android docs](https://developer.android.com/training/articles/perf-tips.html) say that floating point is about half the speed of integer operations on modern Android platforms. Other literature suggests that multiply could be even slower in other environments. And if this code happens to be running on a platform without an FPU, it's game over. – Ted Hopp Oct 28 '16 at 05:58
0

Since you say that 1/2 must be part of the sequence, so be it. (But that's a bizarre sequence and I strongly suggest that you double check this with your professor.) I'll assume that the remainder of the sequence is defined by 1/i2. Note that with these assumptions, the sequence terminates at 1/(n-1)2 rather than 1/n2.

You'll need special handling for the cases n == 1 and n > 1. One possibility is to initialize sum to 1 if n == 1; initialize it to 1.5 if n > 1; and otherwise initialize it to 0. Then start the loop at counter = 2 and change the loop termination condition to counter < n (instead of <=).

Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
0

If that's your sequence then you should really start by setting the sum equal to 1.5 and then rest of it will work. Your sequence should be a geometric sequence 1/n^2 I think it's a mistake.

public static void main(String[]args) {
     Scanner scan = new Scanner(System.in);
        double sum = 1.5;
        int n;

        //input
        System.out.println("Enter n: ");
        n = scan.nextInt();
        if(n==1)
          System.out.println("The sum is: " + 1);
        //process
        for(int counter = 2; counter <n; counter++) {
            double mul = counter*counter;
            sum += 1.0/mul ;
        }

        System.out.println("The sum is: " + sum);

}

Output :

    Enter n: 
    2
    The sum is: 1.5
    Enter n: 
    3
    The sum is: 1.75
thetraveller
  • 445
  • 3
  • 10
0

You need to manage "1" and "2" as special cases.

import java.util.Scanner;
public class Sum
{
    public static void main(String[] args)
    {
    //declarations

        Scanner scan = new Scanner(System.in);
        double sum = 0;
        int n;

        //input
        System.out.println("Enter n: ");
        n = scan.nextInt();

        //process
        for(int counter = 1; counter <= n; counter += 1)
        {
          if (counter == 1)
            sum = 1;
          else if (counter == 2 )
            sum += 1.0/((counter-1)+(counter-1));
          else 
            sum += 1.0 / ((counter-1)*(counter-1)); 
        }

        System.out.println("The sum is: " + sum);
    }
}
80sax
  • 583
  • 4
  • 13
-2

As per your for loop, the sequence generated will be 1 + 1/(2*2) + 1/(3*3)+ ......

So, when you enter 2 => 1+1/(2*2) = 1+0.25=1.25.

Otherwise, your logic is Good. you can implement few exceptions, but as you mentioned that you re new to Java, you ll slowly encounter them.

Happy Learning Java :)

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • The question asked how to get 1.5, though. It should be clarified in the comments above if the sequence should contain `1/2` as a value – OneCricketeer Oct 26 '16 at 23:51
  • Please read the question once againWhen I enter "2" it just gives me the sum of 1.25. How do you get it so when "2" is entered, it is adding 1 + 1/2? – Surendra Kumar S Oct 27 '16 at 00:00
  • 1
    Right. And your "answer" doesn't address OP's question at all. It merely explains the current (undesired) behavior. – Ted Hopp Oct 27 '16 at 00:02
  • 1
    Yeah. Thanks for your suggestion, but I need it so that when the user enters "2" when prompted, it should print out 1.5. When "3" is entered it should be 1.75. – Koulae Moua Oct 27 '16 at 00:05