C++程式:查詢數字的奇數因子的和
給定一個正整數,任務是生成該數字的奇數因子並計算這些奇數因子的和。
示例
Input-: number = 20 Output-: sum of odd factors is: 6 Input-: number = 18 Output-: sum of odd factors is: 13
因此,結果 = 1 + 5 = 6
下面程式中使用的演算法如下 −
- 輸入數字以計算該數字的奇數因子的和
- 忽略數字0和2,因為它們是偶數,並存儲數字1,因為它是奇數
- 從3開始迴圈到數字的平方根
- 遍歷直到number % i 返回0,並繼續用i的值除以number
- 在迴圈中,將臨時變數的值設定為temp = temp * i
- 將total設定為total + temp
- 返回最終res變數的值並列印結果
演算法
START Step 1-> Declare function to calculate sum of odd factors int sum(int num) declare int res = 1 Loop While(num % 2 == 0) set num = num / 2 End Loop For int i = 3 and i <= sqrt(num) and i++ declare int count = 0 and total = 1 declare int temp = 1 Loop while (num % i == 0) count++ set num = num / i set temp *= i set total += temp End set res = res*total End IF (num >= 2) set res *= (1 + num) End return res Step 2-> In main() Declare int num = 20 call sum(num) STOP
示例
#include <bits/stdc++.h> using namespace std; //calculate sum of odd factors int sum(int num) { int res = 1; while (num % 2 == 0) num = num / 2; for (int i = 3; i <= sqrt(num); i++) { int count = 0, total = 1 ; int temp = 1; while (num % i == 0) { count++; num = num / i; temp *= i; total += temp; } res = res*total; } if (num >= 2) res *= (1 + num); return res; } int main() { int num = 20; cout<<"sum of odd factors is : "; cout <<sum(num); return 0; }
輸出
sum of odd factors is : 6
廣告