在 C++ 中找到一个数字的礼貌
在这个问题中,我们给出了一个正整数N。我们的任务是找到一个数字的礼貌。
礼貌数是可以表示为两个或多个连续数之和的数。
一个数字的礼貌被定义为该数字可以表示为连续整数之和的方式的数量。
让我们举个例子来理解这个问题,
输入
n = 5输出结果
1
解释
2 + 3 = 5, is the only consecutive sum.
解决方法
该问题的一个简单解决方案是检查所有连续数字直到N,如果它们的总和等于N,则增加计数,这是数字的礼貌。
该解决方案效率不高,但一个复杂但有效的解决方案是使用因式分解。使用恰好是奇数因素计数乘积的礼貌公式,即
If the number is represented as N = ax * by * cz… Politeness = [(x + 1)*(y +1)*(z + 1)... ] - 1
程序来说明我们的解决方案的工作,
示例
#includeusing namespace std; int calcPolitenessNumber(int n){ int politeness = 1; while (n % 2 == 0) n /= 2; for (int i = 3; i * i <= n; i += 2) { int divCount = 0; while (n % i == 0) { n /= i; ++divCount; } politeness *= divCount + 1; } if (n > 2) politeness *= 2; return (politeness - 1); } int main(){ int n = 13; cout<<"礼貌的 "< 输出结果 礼貌的 13 is 1