Home > Backend Development > C++ > 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
Release: 2023-08-27 11:53:12
forward
799 people have browsed it

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
Copy after login

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
Copy after login

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;
}
Copy after login

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template