ในการหาผลรวมของตัวประกอบคู่ของตัวเลข โค้ด Java มีดังต่อไปนี้ −
ตัวอย่าง
import java.util.*;
import java.lang.*;
public class Demo{
public static int factor_sum(int num){
if (num % 2 != 0)
return 0;
int result = 1;
for (int i = 2; i <= Math.sqrt(num); i++){
int count = 0, current_sum = 1;
int current_term = 1;
while (num % i == 0){
count++;
num = num / i;
if (i == 2 && count == 1)
current_sum = 0;
current_term *= i;
current_sum += current_term;
}
result *= current_sum;
}
if (num >= 2)
result *= (1 + num);
return result;
}
public static void main(String argc[]){
int num = 36;
System.out.println("The sum of even factors of the number is ");
System.out.println(factor_sum(num));
}
} ผลลัพธ์
The sum of even factors of the number is 78
คลาสชื่อ Demo มีฟังก์ชันชื่อ 'factor_sum' ฟังก์ชันนี้ค้นหาตัวประกอบของตัวเลข บวกตัวประกอบคู่และส่งกลับค่านี้เป็นผลลัพธ์ ในฟังก์ชันหลัก จะมีการกำหนดจำนวนที่ต้องการหาตัวประกอบคู่ และฟังก์ชันจะถูกเรียกบนตัวเลขนี้ ข้อความที่เกี่ยวข้องจะแสดงบนคอนโซล