Java Display the Prime Factorization of a number

前端 未结 7 1571
闹比i
闹比i 2020-11-30 13:02

So for my assignment, I have to write a program that asks the user for an integer input and then print out that number\'s prime factorization. This is what I have:



        
7条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-30 13:18

    For one thing, your continue is inside the while loop, where it has no effect whatsoever. The minimal fix would be

    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);
            }
        }
    }
    

    But you have some other problems:

    • Your code is not properly "factored" (ironically, "factored" in this context means that is is not broken up into functions
    • The variable names are poorly chosen
    • You use a goto (continue in this case) when an if would suffice

    Better code would be

    public class PrimeFactor {
        public static void main(String[] args) {
            System.out.print("Enter a positive number: ");
            Scanner scanner = new Scanner (System.in);
            printFactors(scanner.nextInt());
        }
        public static void printFactors(int product) {
            for (int factor = 2; factor <= product; factor++) {
                int exponent = 0;
                while (product % factor == 0) {
                    product /= factor;
                    exponent++;
                }
                if (exponent > 0) {
                    System.out.println(factor+ "**" + exponent);
                }
            }
        }
    }
    

提交回复
热议问题