mdbej
mdbej

Reputation: 103

Calculating sum of odd numbers between two user inputs

I am trying to calculate the sum of the odd numbers between two user inputted numbers.

This is the code I have so far:

import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        System.out.print("#1: ");
        int num1 = s.nextInt();
        System.out.print("#2: ");
        int num2 = s.nextInt();

        int sum = 0;

        for (int i = num1; i <= num2; i += 2) {
            sum = sum + i;
        }

        System.out.print(sum);
    }
}

When I input 3 and 11, it outputs 35, which is correct.

However, with 4 and 20, it outputs 108, which is not correct. It should instead be 96.

Where have I gone wrong in the code?

Upvotes: 2

Views: 4947

Answers (6)

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 79015

If the two numbers are natural numbers, you can apply the formula:

Sum of odd natural numbers from m to n = sum of natural odd numbers up to n - sum of natural odd numbers up to m
                                       = (n/2)^2 - (m/2)^2
                                       where n is an even number or the next even number in case it is an odd number

In the program:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        System.out.print("#1: ");
        int num1 = Math.abs(s.nextInt());
        System.out.print("#2: ");
        int num2 = Math.abs(s.nextInt());       

        System.out.println("Sum of natural odd numbers from "+num1+" to "+num2+" = "+sumNaturalOddOfRange(num1,num2));

        num1 = 5;
        num2 = 15;
        System.out.println("Sum of natural odd numbers from "+num1+" to "+num2+" = "+sumNaturalOddOfRange(num1,num2));

        num1 = 5;
        num2 = 16;
        System.out.println("Sum of natural odd numbers from "+num1+" to "+num2+" = "+sumNaturalOddOfRange(num1,num2));

        num1 = 6;
        num2 = 15;
        System.out.println("Sum of natural odd numbers from "+num1+" to "+num2+" = "+sumNaturalOddOfRange(num1,num2));
    }
    static int sumNaturalOddOfRange(int num1, int num2) {
        if(num2%2==1)
            num2++;
        return (int)(Math.pow(num2 / 2, 2) - Math.pow(num1 / 2, 2));
    }
}

A sample run:

#1: 10
#2: 20
Sum of natural odd numbers from 10 to 20 = 75
Sum of natural odd numbers from 5 to 15 = 60
Sum of natural odd numbers from 5 to 16 = 60
Sum of natural odd numbers from 6 to 15 = 55

Upvotes: 1

WJS
WJS

Reputation: 40034

This can be done easily with a mathematical formula. But based on your question I presume you want to use a loop so here goes.

An odd number has the low order bit set to 1.

If the number is already odd, resetting that bit has no effect so it is still odd.
But setting that bit for an even number makes it the next higher odd number.

So use the bitwise OR operator.

3 | 1 = 3
4 | 1 = 5

And do the following:

      int start = 4;
      int end = 20;
      int sum = 0;

      for (int i = (start | 1); i <= end; i += 2) {
         sum += i;
      }
      System.out.println(sum);

If you want to use streams in Java 8+ you can do it this way.


      int sum = IntStream.rangeClosed(start, end).filter(i -> i & 1 == 1).sum();

And the formula I was talking about is the following, derived using simple series summation.

For ints, start and end

      start |= 1; // ensure start is next odd number
      end = (end | 1) - 2;// ensure end is last odd - 2

      int sum = ((start + end) * ((end - start) / 2 + 1)) / 2;

Upvotes: 2

Andreas
Andreas

Reputation: 159086

To sum a range of numbers:

Take the average of the first number and the last number, and multiply by the number of numbers.

But, first you need to make sure you lower and upper bounds are odd numbers. This is actually what is the problem with the code in the question.

Once that is done, calculate the average number, and the number of numbers:

public static long sumOddNumbers(int min, int max) {
    long minOdd = (min % 2 == 1 ? min : min + 1); // Round up to odd number
    long maxOdd = (max % 2 == 1 ? max : max - 1); // Round down to odd number
    if (minOdd > maxOdd)
        return 0;

    // average = (minOdd + maxOdd) / 2
    // count = (maxOdd - minOdd) / 2 + 1
    // sum = count * average
    return ((maxOdd - minOdd) / 2 + 1) * (minOdd + maxOdd) / 2;
}

Test

System.out.println(sumOddNumbers(3, 11)); // prints: 35
System.out.println(sumOddNumbers(4, 20)); // prints: 96

Upvotes: 2

Arbani Oumaima
Arbani Oumaima

Reputation: 366

**Here is the answer**     
       public static void main(String[] args) {         
            Scanner s = new Scanner(System.in);
            System.out.print("#1: ");
            int num1 = s.nextInt();
            System.out.print("#2: ");
            int num2 = s.nextInt();
            int sum = 0;
            if (num1%2==0) {            
                num1++; 
            }

           for (int i = num1; i <= num2; i++) {

                sum +=i;

    }


    System.out.print(sum);  
    }

Upvotes: 0

Eray Balkanli
Eray Balkanli

Reputation: 7960

You need to check if the first number is even or odd first, because if it is even, it is going to sum the even numbers instead of odd ones since you are increasing "i" by 2 after every iteration. Try adding the line below before the for loop.

if(num1%2==0){num1++);

Upvotes: 2

Zabuzard
Zabuzard

Reputation: 25903

Explanation

Your loop sums the even numbers if you start with an even number.

Check your code:

for (int i = num1; i <= num2; i += 2)

Assume num1 is even, e.g. 4. Then your loop starts with i = 4. And then you continue with += 2, so you end up with 6, 8, 10, ..., i.e. the even numbers.


Solution

You can simply fix it by patching num1 before your loop.

// Put this before your loop
if (num1 % 2 == 0) { // checks if num1 is even
    num1++;
}

This way you will start with 5 then, and then get 7, 9, 11, ....

Upvotes: 2

Related Questions