본문 바로가기

Algorithms/30 Days of Code

Day 19: Interfaces

Task 
The AdvancedArithmetic interface and the method declaration for the abstract int divisorSum(int n) method are provided for you in the editor below. Write the Calculator class, which implements the AdvancedArithmeticinterface. The implementation for the divisorSum method must be public and take an integer parameter, , and return the sum of all its divisors.

Note: Because we are writing multiple classes in the same file, do not use an access modifier (e.g.: public) in your class declaration (or your code will not compile); however, you must use the public access modifier before your method declaration for it to be accessible by the other classes in the file.

Input Format

A single line containing an integer, .

Constraints

Output Format

You are not responsible for printing anything to stdout. The locked Solution class in the editor below will call your code and print the necessary output.

Sample Input

6

Sample Output

I implemented: AdvancedArithmetic
12

Explanation

The integer  is evenly divisible by , and . Our divisorSum method should return the sum of these numbers, which is . The Solution class then prints  on the first line, followed by the sum returned by divisorSum (which is ) on the second line.


풀이


package Day19;

interface AdvancedArithmetic {
int divisorSum(int n);
}


package Day19;

class Calculator implements AdvancedArithmetic {
@Override
public int divisorSum(int n) {
int sum = 0;
for (int i = 1; i <= n; i++) {
if (n % i == 0)
sum += i;
}
return sum;
}
}


package Day19;

import java.util.Scanner;

class Solution {

public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
scan.close();

AdvancedArithmetic myCalculator = new Calculator();
int sum = myCalculator.divisorSum(n);
System.out.println("I implemented: " + myCalculator.getClass().getInterfaces()[0].getName());
System.out.println(sum);
}
}


'Algorithms > 30 Days of Code' 카테고리의 다른 글

Day 21: Generics  (0) 2018.03.08
Day 20: Sorting  (0) 2018.03.08
Day 18: Queues and Stacks  (0) 2018.02.27
Day 17: More Exceptions  (0) 2018.02.27
Day 16: Exceptions - String to Integer  (0) 2018.02.27