在 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