[Programmers / JAVA] Level 1 Sum of Divisors (12928)
[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.
@RWBwritten at 2021-12-18 09:13:33
| Rank | Language Used |
|---|---|
| Level 1 | 🖼️ JAVA |
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.
| n | return |
|---|---|
| 12 | 28 |
| 5 | 6 |
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
