Home  >  Article  >  Backend Development  >  C program to find the smallest sum of factors of a number?

C program to find the smallest sum of factors of a number?

WBOY
WBOYforward
2023-08-27 11:53:12763browse

C program to find the smallest sum of factors of a number?

This program is used to find the smallest sum of factors of a number. The logic to solve this problem is to find all sets of factors and add them up. We do the same thing for each set of factors and then compare them all. Then find all minima of these sums.

Input: n=12
Output: 7

Explanation

First find the factors of the number n, then add them and try to minimize the sum. Here are the different ways to factor 12 and the sum of the factors.

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;
}

The above is the detailed content of C program to find the smallest sum of factors of a number?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete