怎样用java实现以上程序
时间: 2024-09-25 19:08:51 浏览: 24
以下是用Java分别实现上述四个问题的简单示例:
1. 寻找1-1000内能被3和7整除的数:
```java
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 1000; i++) {
if (i % 21 == 0) {
System.out.println(i);
}
}
}
}
```
2. 计算阶乘之和 (利用循环):
```java
public int factorialSum(int n) {
long sum = 0;
for (int i = 1; i <= n; i++) {
sum += factorial(i);
}
return (int) sum; // 注意长整型溢出,这里转换为int类型
}
private long factorial(int n) {
if (n == 0 || n == 1) return 1;
return n * factorial(n - 1);
}
```
3. 检查奇数个数:
```java
public int countOddNumbers(int[] numbers) {
int oddCount = 0;
for (int num : numbers) {
if (num != 0 && num != -1 && num % 2 != 0) {
oddCount++;
} else {
break;
}
}
return oddCount;
}
```
4. 判断素数:
```java
public boolean isPrime(int n) {
if (n <= 1) return false;
if (n <= 3) return true;
if (n % 2 == 0 || n % 3 == 0) return false;
for (int i = 5; i * i <= n; i += 6) {
if (n % i == 0 || n % (i + 2) == 0) {
return false;
}
}
return true;
}
```
阅读全文