Java程式查詢數字的偶數因數之和
在這篇文章中,我們將使用Java查詢給定數字的偶數因數之和。我們將首先檢查數字是否為偶數,然後識別其所有因數,將偶數因數加起來,最後顯示結果。
問題陳述
編寫一個Java程式來查詢數字的偶數因數之和。以下是相同的演示 -
輸入
num=16
輸出
The sum of even factors of the number is
30
查詢數字的偶數因數之和的步驟
以下是查詢數字的偶數因數之和的步驟 -
- 從匯入所需的類開始。
- 檢查數字是否為偶數,返回0。
- 對數字進行因式分解,我們將使用一個迴圈來查詢直到數字平方根的所有因數。
- 將偶數因數加起來
- 顯示偶數因數之和。
Java程式查詢數字的偶數因數之和
要查詢數字的偶數因數之和,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
程式碼解釋
首先,我們將從java.util和java.lang包中匯入所有類,之後我們將初始化一個名為Demo的類,其中包含一個名為“factor_sum”的函式。它首先檢查數字是否為偶數。如果不是,則返回0。使用for迴圈,它迭代可能的因數,並且巢狀的while迴圈對數字進行因式分解。它更新偶數因數之和,並且在迴圈之後,它將結果乘以任何剩餘的素因數。main方法初始化數字呼叫factor_sum並列印結果。
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP