在C ++中将N除以除数后的最大和
在这个问题中,我们得到一个整数N。我们的任务是创建一个程序,该程序在C++中将N反复除以除数后将找到最大和。
程序说明-我们将递归除数N,直到其变为1,然后将所有除数求和,找到所有除数的最大值。
让我们举个例子来了解这个问题,
输入-N=12
输出-22
解释-让我们递归除数并求和。
Division 1: 12/2 = 6 Division 2: 6/2 = 3 Division 3: 3/3 = 1 Sum = 12+6+3+1 = 22
为了解决这个问题,我们可以通过将N除以N的最小除数来最大化各个值,从而找到最大的和。
示例
程序来说明我们的解决方案的工作原理,
#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;
}输出结果
The maximum sum after repeatedly dividing 12 by divisor is 22
热门推荐
10 送给情侣贺卡祝福语简短
11 项目建设春节祝福语简短
12 叔叔生日祝福语简短搞笑
13 英文写结婚祝福语简短
14 简短有内涵的祝福语
15 新年恋人祝福语简短创意
16 恭喜新郎父母简短祝福语
17 道教生日祝福语简短大全
18 送给员工美好祝福语简短