软工博客15
数学小工具:
package com.example;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class App {
// 计算阶乘
public static long factorial(int n) {
if (n < 0) {
throw new IllegalArgumentException("阶乘只能计算非负整数");
}
long result = 1;
for (int i = 2; i <= n; i++) {
result *= i;
}
return result;
}
// 判断质数
public static boolean isPrime(int n) {
if (n <= 1) {
return false;
}
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
// 合并两个列表并去重
public static List<Integer> mergeAndDistinct(List<Integer> list1, List<Integer> list2) {
Set<Integer> set = new HashSet<>(list1);
set.addAll(list2);
return new ArrayList<>(set);
}
// 查找列表中的最大值
public static int findMax(List<Integer> list) {
if (list == null || list.isEmpty()) {
throw new IllegalArgumentException("列表不能为空");
}
int max = list.get(0);
for (int num : list) {
if (num > max) {
max = num;
}
}
return max;
}
public static void main(String[] args) {
// 测试阶乘
System.out.println("5 的阶乘是: " + factorial(5));
// 测试质数判断
System.out.println("7 是否是质数: " + isPrime(7));
System.out.println("10 是否是质数: " + isPrime(10));
// 测试合并列表并去重
List<Integer> list1 = List.of(1, 2, 3, 4);
List<Integer> list2 = List.of(3, 4, 5, 6);
List<Integer> mergedList = mergeAndDistinct(list1, list2);
System.out.println("合并后的列表: " + mergedList);
// 测试查找最大值
System.out.println("列表中的最大值: " + findMax(mergedList));
}
}

浙公网安备 33010602011771号