Java (Algebra: perfect square) Write a program that prompts the user to enter an integer m and find the smallest integer n such that m * n is a perfect square. (Hint: Store all smallest factors of m into an array list. n is the product of the factors that appear an odd number of times in the array list. For example, consider m = 90, store the factors 2, 3, 3, and 5 in an array list. 2 and 5 appear an odd number of times in the array list. Thus, n is 10.)
时间: 2023-11-22 13:53:44 浏览: 71
这是用Java写的计算器小程序
Here's the Java code to solve the problem:
```
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();
ArrayList<Integer> factors = new ArrayList<Integer>();
int factor = 2;
while (factor <= m) {
if (m % factor == 0) {
factors.add(factor);
m /= factor;
}
else {
factor++;
}
}
int n = 1;
for (int i = 0; i < factors.size(); i++) {
int count = 1;
for (int j = i + 1; j < factors.size(); j++) {
if (factors.get(i) == factors.get(j)) {
count++;
}
}
if (count % 2 != 0) {
n *= factors.get(i);
}
}
System.out.println("The smallest integer n such that m * n is a perfect square is: " + n);
}
}
```
Explanation:
1. We first prompt the user to enter an integer `m` using the `Scanner` class.
2. We then create an `ArrayList` called `factors` to store all the smallest factors of `m`.
3. We use a `while` loop to find all the smallest factors of `m`. If `m` is divisible by `factor`, we add it to the `factors` list and divide `m` by `factor`. Otherwise, we increment `factor` by 1.
4. We then use two nested `for` loops to check how many times each factor appears in the `factors` list. If a factor appears an odd number of times, we multiply it with `n`.
5. Finally, we print out the value of `n`.
阅读全文