Day 19 Interfaces Hackerrank Solution in C++ | 30 Days of Code

Day 19 Interfaces Hackerrank Solution in C++. 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 the Calculator class, which implements the AdvancedArithmetic interface. The implementation for the divisorSum(n) method must return the sum of all divisors of n.

This is a very simple problem(Interfaces) we have to just calculate the divisor sum and print the sum of the divisor. we can do this by running the loop(starting with 1 and ending with N) and putting the condition if number N is divided by I(where I = 1 to N) then the sum of the divisor is added each time when if N%I==0. Let's take an example and try to understand the problem step by step.

Example: Let's assume Number N is 24 and we have to calculate the Divisor sum so we divide the number by I=1 to I=24 with the help of "For Loop" Take a look at step by step.

Step 1: If(N % I ==0) then Sum or total is Sum = Sum + I Or Total = Total + I.

Step 2: Print the total outside the "For Loop". Here Divisor of 24 = 1 + 2 + 3 + 4 + 6 + 8 + 12 + 24 = 60.

Day 19 Interfaces Hackerrank Solution in C++

``````#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
{
public:
virtual int divisorSum(int n) = 0;
};

{
public: int divisorSum(int n)
{
int sum = n;

for (int i = 1; i < ceil(n / 2) + 1; i++)
n % i ? 1 : sum += i;

return sum;
}
};

int main()
{
int n;
cin >> n;
int sum = myCalculator->divisorSum(n);
cout << "I implemented: AdvancedArithmetic\n" << sum;
return 0;
}``````

Previous Post
Next Post