Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write a method to work out the sum of the first n odd numbers

Tags:

java

loops

sum

First of all let me say I am quite new to programming its been my second week since I started so if you see any bad practice or error in code please accept my apologies.

I want to print sum of first n odd numbers. But so far I can only do the sum of odd number up to the given number. kindly help.

public static void main(String[] args) 
{
    Scanner userInput = new Scanner(System.in);

    System.out.print("Please enter the number : ");
    int num1 = userInput.nextInt();

    int sum = sumOfOdd(num1);
    System.out.println("sum of first " +num1 + " odd numbers is " + sum);

    userInput.close();
}

static int sumOfOdd(int num)
{
    int sum = 0;
    for (int i = 0; i <= num; i++)
    {
        if(i % 2 != 0)
        {
            sum += i;
        }
    }
    return sum;
}
}
like image 756
elseshawe Avatar asked Dec 05 '22 13:12

elseshawe


1 Answers

You don't have to use a loop at all

static int sumOfOdd(int num) {
    return num*num;
}

For Any Arithmetic Progression, the sum of numbers is given by,

Sn=1/2×n[2a+(n-1)×d]

Where,

Sn= Sum of n numbers

n = n numbers

a = First term of an A.P

d= Common difference in an A.P

Using above formula we can derive this quick formula to calculate sum of first n odd numbers,

Sn(odd numbers)= n²

like image 180
Isuranga Perera Avatar answered Feb 16 '23 00:02

Isuranga Perera