**11.17 (代数: 完全平方)编写一个Java程序,提示用户输人一个整数m,然后找到最小的整数n,使得 m*n是一个完全平方。 提示:存储所有m的最小因子到一个数组列表,则n是列表中出现奇数次的因子的乘积。例如,考虑m=90的情况,保存因子2,3,3,5到一个数组列表中。列表中2和5出现了奇数次数,因此,n是10。) 这里是一个运行示例: . Enter an integer m: 1500 The smallest number n for m * n to be a perfect square is 15 m×n is 22500 Enter an integer m: 63 The smalle st number n for m*n to be a perfect square is 7 m*n is 441
时间: 2024-03-03 12:50:57 浏览: 158
好的,以下是Java程序的代码:
```java
import java.util.ArrayList;
import java.util.Scanner;
public class PerfectSquare {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer m: ");
int m = input.nextInt();
input.close();
ArrayList<Integer> factors = new ArrayList<Integer>();
int factor = 2;
while (m != 1) {
if (m % factor == 0) {
factors.add(factor);
m /= factor;
} else {
factor++;
}
}
int n = 1;
for (int i = 0; i < factors.size(); i++) {
if (i == 0 || factors.get(i) != factors.get(i - 1)) {
if (Collections.frequency(factors, factors.get(i)) % 2 == 1) {
n *= factors.get(i);
}
}
}
System.out.println("The smallest number n for m * n to be a perfect square is " + n);
System.out.println("m * n is " + m * n);
}
}
```
示例输出:
```
Enter an integer m: 1500
The smallest number n for m * n to be a perfect square is 15
m * n is 22500
Enter an integer m: 63
The smallest number n for m * n to be a perfect square is 7
m * n is 441
```
阅读全文