Prime factorization of Java display numbers
•
Java
Therefore, for my task, I must write a program that requires the user to input an integer, and then print out the prime factorization of the number
import java.util.Scanner; public class PrimeFactor { public static void main(String[] args) { System.out.print("Enter a positive number: "); Scanner scanner = new Scanner (system.in); int number = scanner.nextInt(); int count; for (int i = 2; i<=(number); i++) { count = 0; while (number % i == 0) { number /= i; count++; if (count == 0) { continue; } } System.out.println(i+ "**" + count); } } }
The problem I'm facing now is that whenever I run it, such as 15453, I get a list of each factor from 1 to 100 and its index. When I just think about the factor factor factor, I'm trapped in how to continue
Solution
You're almost there! Move the if - continue block out of the for loop Otherwise, it will "continue" the innermost loop, not the loop you want
while (number % i == 0) { number /= i; count++; } if (count == 0) { continue; } System.out.println(i+ "**" + count);
Alternatively, you can include system. In if (count! = 0) out. Println is called because it is the only statement to continue:
while (number % i == 0) { number /= i; count++; } if (count != 0) { System.out.println(i+ "**" + count); }
Your program on ideone: link
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码