blog.itcode.devblog.itcode.dev

[Programmers / JAVA] Level 1 Sum of Divisors (12928)

Complete the function solution, which takes an integer n and returns the sum of all divisors of n.

[Programmers / JAVA] Level 1 Sum of Divisors (12928)

Complete the function solution, which takes an integer n and returns the sum of all divisors of n.
RWB0104
@RWBwritten at 2021-12-18 09:13:33
Programmers

시리즈 모아보기

Programmers

49 / 78
RankLanguage Used
Level 1

🖼️ JAVA

🔗 Sum of Divisors

Complete the function solution, which takes an integer n and returns the sum of all divisors of n.

  • n is an integer between 0 and 3000, inclusive.
nreturn
1228
56

Input/Output Example #1

The divisors of 12 are 1, 2, 3, 4, 6, and 12. Adding them all gives 28.

Input/Output Example #2

The divisors of 5 are 1 and 5. Adding them gives 6.

Find the divisors and accumulate their values. The algorithm for finding divisors is as follows.

JAVA

for (int i = 1; i <= Math.sqrt(n); i++)
{
	// If it divides evenly
	if (n % i == 0)
	{
		// If it is the square root of n
		if (i * i == n)
		{
			answer += i;
		}
		
		// If it is not the square root of n
		else
		{
			answer += i;
			answer += n / i;
		}
	}
}

By iterating up to the square root of n, you can find all its divisors.

JAVA

/**
 * Sum of Divisors class
 *
 * @author RWB
 * @since 2021.12.13 Mon 17:52:04
 */
class Solution
{
	/**
	 * Method that returns the answer
	 *
	 * @param n: [int] integer
	 *
	 * @return [int] answer
	 */
	public int solution(int n)
	{
		int answer = 0;
		
		for (int i = 1; i <= Math.sqrt(n); i++)
		{
			// If it divides evenly
			if (n % i == 0)
			{
				// If it is the square root of n
				if (i * i == n)
				{
					answer += i;
				}
				
				// If it is not the square root of n
				else
				{
					answer += i;
					answer += n / i;
				}
			}
		}
		
		return answer;
	}
}
# Programmers# Algorithm# JAVA# Level 1
ship
blog.itcode.dev

Notes from the π-th Alpaca

7.0.1
Developed by RWB since 2021.057th upgraded at 2026.08