Maximum sum after repeatedly dividing N by a divisor in C++


In this problem, we are given an integer N. Our task is to create a program that will find the maximum sum after repeatedly dividing N by a divisor in C++.

Program description − we will divide the number N recursively until it becomes one and then sum up all the divisors and find the maximum of all divisors.

Let’s take an example to understand the problem,

Input − N = 12

Output − 22

Explanation − let’s divide the number recursively and find the sum.

Division 1: 12/2 = 6
Division 2: 6/2 = 3
Division 3: 3/3 = 1
Sum = 12+6+3+1 = 22

To solve this problem, we will find the maximum sum by making the maximum of the individual values by dividing N by the smallest divisor of N.

Example

Program to illustrate the working our solution,

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int smallestDivisor(int n){
   int mx = sqrt(n);
   for (int i = 2; i <= mx; i++)
      if (n % i == 0)
         return i;
   return n;
}
int calculateMaxSum(int n) {
   long long maxSum = n;
   while (n > 1) {
      int divisor = smallestDivisor(n);
      n /= divisor;
      maxSum += n;
   }
   return maxSum;
}
int main(){
   int N = 12;
   cout<<"The maximum sum after repeatedly dividing "<<N<<" by divisor is "<<calculateMaxSum(N);
   return 0;
}

Output

The maximum sum after repeatedly dividing 12 by divisor is 22

Updated on: 03-Jun-2020

65 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements