C Program to Find the minimum sum of factors of a number?


The program to find the minimum sum of factors of a number. The logic for solving this problem is, find all the set of factors and adding them. For every set of factors, we will do the same and then compare all of them. Then find all the minimum of these sums.

Input: n=12
Output: 7

Explanation

First find the factors of number n then sum them and try to minimize the sum. Following are different ways to factorize 12 and sum of factors in different ways.

12 = 12 * 1 = 12 + 1 = 13
12 = 2 * 6 = 2 + 6 = 8
12 = 3 * 4 = 3 + 4 = 7
12 = 2 * 2 * 3 = 2 + 2 + 3 = 7
Therefore minimum sum is 7

Example

#include<iostream>
using namespace std;
int main() {
   int n = 12;
   int sum = 0;
   for (int i = 2; i * i <= n; i++) {
      while (n % i == 0) {
         sum += i;
         n /= i;
      }
   }
   sum += n;
   cout << sum;
   return 0;
}

Updated on: 20-Aug-2019

262 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements