Sum of all divisors of a number.

In this article, we are going to find the sum of all divisors of a given number.

Example:-

if number = 6, then the output will be 1+2+3+6=12.

Steps:-

  • Take a input from user using scanner.
  • Take a variable to store sum of all divisors and initialize it to 0.
  • Run a loop from i=1 to i<=n.
  • Check if n is divisible by i then sum =sum+i.
  • End of loop.
  • print sum.

Java code to find the sum of all divisors of a given number:-

package gangforcode;

import java.util.Scanner;

public class SumofallDivisors {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.println("Enter the number");
		int n=sc.nextInt();
		int sum=0;
		for(int i=1;i<=n;i++) {
			if(n%i==0) {
				sum=sum+i;
			}
			}
		System.out.println(sum);
	}

}

Output:-

Java code to find sum of all divisors of a given number

You can use the same logic to find the sum of all divisors of a given number using other programming languages like C, C++, and Python, etc.

Leave a Comment