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