The Wayback Machine - https://web.archive.org/web/20220218143306/https://www.geeksforgeeks.org/find-sum-of-values-of-n-at-each-step-after-repeatedly-dividing-it-with-its-smallest-factor/
Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Find sum of values of N at each step after repeatedly dividing it with its smallest factor

  • Last Updated : 18 Feb, 2022

Given an integer N, the task is to find the sum of all values of N after repeatedly dividing it with its smallest factor.

Examples:

Input: N = 5
Output: 6
Explanation: Initially N = 5. The smallest factor of N is 5 itself. Therefore, the value of N will become N/5 = 5/5 = 1. Hence, the sum of all values of N is 5 + 1 = 6.

Input: N = 10.
Output: 16
Explanation: Initially N = 10. The smallest factor of N is 2. Therefore, the value of N will become N/2 = 10/2 = 5. Similarly, in next step, N = N/5 = 5/5 = 1. Hence, the sum of all values of N is 10 + 5 + 1 = 16.

Approach: The given problem is an implementation-based problem and can be solved by iterating in the range [2, √N] and dividing N with its smallest factor, maximum possible times. Maintain the sum of all values of N in a variable which will be the required answer.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
  
// Function to find the sum of all the
// values of N after repeatedly dividing
// it with its smallest factor
int sumValues(int N)
{
    // Stores the required answer
    int ans = N;
  
    int i = 2;
  
    // Loop to iterate over
    // the factors of N
    while (N > 1) {
  
        // If i is a factor
        if (N % i == 0) {
  
            // Update N
            N = N / i;
  
            // Update ans
            ans += N;
        }
        else {
            i++;
        }
    }
  
    // Return Answer
    return ans;
}
  
// Driver function
int main()
{
    int N = 10;
    cout << sumValues(N);
    return 0;
}
Output
16

Time Complexity: O(√N)
Auxiliary Space: O(1)


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!