0
2.9kviews
Write the algorithm to find the sum of series and also find its time complexity where


Write the algorithm to find the sum of series and also find its time complexity where

$s=\sum_{i=1}^{n}i2$

1 Answer
0
64views

Our work is to write an algorithm to find the sum of the series and the series is -


$ $ $S = ∑^{n}_{i=1}=i^2$



//Importing the library
import java.util.*;

public class solve {
    public static void main(String[] args) {

        //Taking n as an input
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter the value of n: ");
        int n = sc.nextInt();

        //Initialising sum as 0
        int sum = 0;

        //calculating the total sum of series
        for(int i=1; i<=n; i++){
            sum += (i*i);
        }

        //Printing the result i.e. total sum of the series
        System.out.println(sum);
    }
}
//Enjoy Coding.....



Time Complexity for the above algorithm : -

Since we are initialising a for loop which is running from 1 to n.

So, the time complexity will be linear(as n varies) O(n).

Hence, Time Complexity = O(n).

1

Time complexity will be linear, not constant


Please log in to add an answer.