Friday 29 September 2017

Java method that takes an integer n and returns the sum of the squares of all positive integers less than or equal to n.

Problem:

Write a short Java method that takes an integer n and returns the sum of the
squares of all positive integers less than or equal to n.

Solution:

package com.basics;

import java.util.Scanner;

public class SumOfSquares {

static int number;

public static void main(String[] args) {
SumOfSquares findSum = new SumOfSquares();
findSum.getTheNumber();
System.out.println("the sum of the squares of all positive integers less than or equal to n is:  " + findSum.findSum(number));

}

public void getTheNumber(){
Scanner scanner = new Scanner(System.in);
System.out.println("enter the number");
number = scanner.nextInt();
scanner.close();
}

public int findSum(int number){
int sum = 0;
for (int i = 1; i <= number; i++) {
sum = sum + (i * i);
}
return sum;
}

}


Output:

enter the number
4
the sum of the squares of all positive integers less than or equal to n is:  30


No comments:

Post a Comment

Program for primality test in JAVA

Problem: ============= Program for primality test in JAVA What is primality test? A primality test is an algorithm for determining wh...