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.) Here are some sample runs: Enter an integer m: 1500 The smallest number n for m * n to be a perfect square is 15 m * n is 22500
时间: 2023-07-16 18:16:42 浏览: 112
Here's the Java code to solve this problem:
```
import java.util.*;
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();
List<Integer> factors = getSmallestFactors(m);
int n = 1;
for (int factor : factors) {
if (getFrequency(factors, factor) % 2 != 0) {
n *= factor;
}
}
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 * n));
}
public static List<Integer> getSmallestFactors(int n) {
List<Integer> factors = new ArrayList<>();
int factor = 2;
while (n > 1) {
if (n % factor == 0) {
factors.add(factor);
n /= factor;
} else {
factor++;
}
}
return factors;
}
public static int getFrequency(List<Integer> list, int value) {
int count = 0;
for (int element : list) {
if (element == value) {
count++;
}
}
return count;
}
}
```
Explanation:
The `getSmallestFactors` method takes an integer `n` as input and returns a list of its smallest factors. It does this by repeatedly dividing `n` by its smallest factor until `n` becomes 1.
The `getFrequency` method takes a list of integers and a value as input and returns the number of times the value appears in the list.
In the `main` method, we first prompt the user to enter an integer `m`. Then we call `getSmallestFactors` to get the list of smallest factors of `m`. We then iterate through the list of factors and multiply the ones that appear an odd number of times. This gives us the smallest integer `n` such that `m * n` is a perfect square. Finally, we print out the value of `n` and `m * n * n`.
阅读全文