1.定义一个类,里面实现判断是否是水仙花数和判断数据是否是质数 2.定义另一个类,利用随机函数生成1000个随机数; 3.定义一个类,里面实现按照冒泡排序、快速排序对数据进行排序的算法
时间: 2024-10-28 16:07:41 浏览: 43
首先,我们来看一下如何定义这三个类:
1. **水仙花数和质数检查类**:
```java
public class NumberUtils {
public boolean isPerfectNumber(int num) {
if (num <= 1) return false;
int sum = 0;
for (int i = 1; i * i <= num; i++) {
if (num % i == 0) {
sum += i;
if (i != num / i) // 如果还有其他因子
sum += num / i;
}
}
return sum == num && num != 1;
}
public boolean isPrime(int num) {
if (num <= 1) return false;
for (int i = 2; i * i <= num; i++) {
if (num % i == 0)
return false;
}
return true;
}
}
```
2. **随机数生成类**:
```java
import java.util.Random;
public class RandomNumberGenerator {
private static final int COUNT = 1000;
public static void generateRandomNumbers() {
Random rand = new Random();
int[] randomNumbers = new int[COUNT];
for (int i = 0; i < COUNT; i++) {
randomNumbers[i] = rand.nextInt(10000); // 生成0到9999之间的整数
}
System.out.println("Generated " + COUNT + " random numbers.");
}
}
```
3. **排序算法类**:
```java
public class SortingAlgorithms {
public void bubbleSort(int[] arr) {
// 冒泡排序实现
for (int i = 0; i < arr.length - 1; i++) {
for (int j = 0; j < arr.length - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
public void quickSort(int[] arr, int low, int high) {
// 快速排序实现
if (low < high) {
int pivotIndex = partition(arr, low, high);
quickSort(arr, low, pivotIndex - 1);
quickSort(arr, pivotIndex + 1, high);
}
}
// 辅助方法用于快速排序的划分操作
private int partition(int[] arr, int low, int high) {
//...
}
}
```
阅读全文