用java写1、将一个正整数分解质因数。例如:输入90,打印出90=2*3*3*5。 程序分析:对n进行分解质因数,应先找到一个最小的质数k,然后按下述步骤完成: (1)如果这个质数恰等于n,则说明分解质因数的过程已经结束,打印出即可。 (2)如果n<>k,但n能被k整除,则应打印出k的值,并用n除以k的商,作为新的正整数n,重复执行第一步。 (3)如果n不能被k整除,则用k+1作为k的值,重复执行第一步。 2、输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。
时间: 2024-03-16 07:47:16 浏览: 14
好的,下面是用Java实现题目要求的代码:
1、将一个正整数分解质因数
```java
import java.util.Scanner;
public class PrimeFactorization {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入一个正整数:");
int n = scanner.nextInt();
System.out.print(n + "=");
int k = 2;
while (k <= n) {
if (k == n) {
System.out.print(k);
break;
}
if (n % k == 0) {
System.out.print(k + "*");
n /= k;
} else {
k++;
}
}
}
}
```
2、输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数
```java
import java.util.Scanner;
public class CountCharacters {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入一行字符:");
String str = scanner.nextLine();
int letterCount = 0;
int spaceCount = 0;
int digitCount = 0;
int otherCount = 0;
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z') {
letterCount++;
} else if (ch == ' ') {
spaceCount++;
} else if (ch >= '0' && ch <= '9') {
digitCount++;
} else {
otherCount++;
}
}
System.out.println("字母个数:" + letterCount);
System.out.println("空格个数:" + spaceCount);
System.out.println("数字个数:" + digitCount);
System.out.println("其他字符个数:" + otherCount);
}
}
```