Java Program To Get The Sum Of All The Divisors Of A Number

By Saruque Ahamed Mollick

Here is the easy Java Program to print the summation of all the divisors of an integer number.

That means, suppose we have an Integer: 12 as input

The divisors of 12 are, 1,2,3,4,6,12

The sum of all the divisors is: 1+2+3+4+6+12=28

So the output of our program should be like this: 28

Here is the program:



import java.util.Scanner;
public class Codespeedy {
  public static void main(String[] args) {
    Scanner input=new Scanner(System.in);
    System.out.println("Enter the number:");
    int number=input.nextInt();
    int j = 0;
    
         for(int i = 1; i <= number; i++) {
             if (number % i == 0) {
                 j = j + i; 
             }
             
         
         }
         System.out.println("The Sum Of The Divisors is: ");
         System.out.println(j);
}
}

“if(number % i == 0)”
it means if the number is divisible by “i” then it will execute this part “j=j+i”
and by j+1 it will store the summation of all divisible integers.
The loop will continue until “i” reaches the value of the entered number. Thus it will check all the numbers and the numbers which are divisible will be added with “j”. Finally, the value of “j” will be printed which is the summation of all the divisors of a given number entered by the user in runtime.
example:
Input: 15

Output:

Enter the number:
15
The Sum Of The Divisors is:
24

Leave a Reply

Your email address will not be published. Required fields are marked *