Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Chương trình Java tìm tổng các ước số chẵn của một số


Để tìm tổng các ước số chẵn của một số, mã Java như sau:

Ví dụ

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));    } }

Kết quả

The sum of even factors of the number is 78

Lớp Demo chứa hàm factor_sum. Hàm tìm ước của số, cộng các ước chẵn và trả về giá trị. Trong main, số cần tìm ước chẵn định nghĩa, hàm gọi trên số này. Thông báo hiển thị.