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
广告