Write a program that prompts the user to enter an interger m and find the smalle
ID: 3759474 • Letter: W
Question
Write a program that prompts the user to enter an interger 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, 5 in an array list. 2 and 5 appear an odd number of times in the array list. So, n is 10. Here are 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
Enter an integer m: 63
The smallest number n for m * n to be a perfect sqaure is 7 m * n is 441
Explanation / Answer
import java.util.*;
public class PerfectSquare {
public static void main(String[] args) {
ArrayList<Integer> array = new ArrayList<>();
Scanner INT = new Scanner(System.in);
int[] arrayone = new int[25];
System.out.println("Please enter an integer m: ");
int m = INT.nextInt();
int k = m;
for (int i = 2; i < m; i++) {
while(m%i==0) {
array.add(i);
m /= i;
}
}
for (Integer array1 : array)
{arrayone[array1]++;
}
int n = 1;
for (int i = 0; i<25; i++)
{if(arrayone[i]%2!=0)
n = n*i;
}
System.out.println("The smallest number n for m * n to be perfect square is " + n);
System.out.println("m * n is: " + (k * n));
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.