Day 19: Interfaces
Aim
Hey CodingHumans today, we're learning about Interfaces.
An interface is a collection of abstract methods and constants that form a common set of base rules/specifications for those classes that implement it. Much like an abstract class, an interface cannot be instantiated and must be implemented by a class.
Task
The AdvancedArithmetic interface and the method declaration for the abstract divisorSum(n) method are provided for you in the editor below.
Complete the implementation of Calculator class, which implements the AdvancedArithmetic interface. The implementation for the divisorSum(n) method must return the sum of all divisors of .
Input Style
A single line containing an integer, .
Constraints
1<=n<=1000
Output Style
You are not responsible for printing anything to stdout. The locked template code 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 6 is evenly divisible by 1,2 ,3 ,4 and 6 . Our divisorSum method should return the sum of these numbers, which is 1+2+3+6=12. The Solution class then prints I implemented:AdvanceArithmetic on the first line, followed by the sum returned by divisorSum (which is 12) on the second line.
Recommended: Please try your approach on your integrated development environment (IDE) first, before moving on to the solution.
Few words from CodingHumans : Don't Just copy paste the solution, try to analyze the problem and solve it without looking by taking the the solution as a hint or a reference . Your understanding of the solution matters.
HAPPY CODING 😁
( Java )
import java.io.*; import java.util.*; interface AdvancedArithmetic{ int divisorSum(int n); } class Calculator implements AdvancedArithmetic { public int divisorSum(int n) { int sum=0; for(int i=1;i<=n;i++) if(n%i==0) sum=sum+i; return sum; } } 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); } }
If you have any doubts regarding this problem or need the solution in other programming languages then leave a comment down below .