在 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
程序举例说明我们解决方案的工作原理,
示例
#include <iostream>
using 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<<"Politeness of "<<n<<" is "<<calcPolitenessNumber(n);
return 0;
}输出
Politeness of 13 is 1
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP