กำหนดด้วยจำนวนเต็มบวกและภารกิจคือการสร้างตัวประกอบคี่ของตัวเลขและหาผลรวมของปัจจัยคี่ที่ให้มา
ตัวอย่าง
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 จนถึงรากที่สองของตัวเลข
- สำรวจจนถึงตัวเลข % i กำลังคืนค่า 0 และหารตัวเลขด้วยค่าของ i ต่อไป
- ในลูปให้ตั้งค่าตัวแปรชั่วคราวเป็น temp =temp * i
- ตั้งค่าผลรวมเป็นยอด + อุณหภูมิ
- คืนค่าตัวแปร 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