กำหนดจำนวนเต็มบวก และภารกิจคือสร้างตัวประกอบคี่ของจำนวนนั้นและหาผลรวมของตัวประกอบคี่ที่ได้
ตัวอย่าง
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
- ในลูป ตั้งค่าตัวแปรชั่วคราวเป็น temp = temp * i
- ตั้งค่า total = total + temp
- คืนค่าตัวแปร res สุดท้ายและพิมพ์ผลลัพธ์
อัลกอริทึม
เริ่มต้น ขั้นตอนที่ 1 -> ประกาศฟังก์ชันคำนวณผลรวมตัวประกอบคี่ 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 จบ ถ้า (num >= 2) ตั้งค่า res *= (1 + num) จบ คืนค่า res ขั้นตอนที่ 2 -> ใน main() ประกาศ int num = 20 เรียก sum(num) จบ
ตัวอย่าง
#include <bits/stdc++.h> using namespace std; // คำนวณผลรวมตัวประกอบคี่ 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