Unique factorization with counter

浪尽此生 提交于 2019-12-20 07:53:56

问题


I am trying to build a program in JAVA which uses Unique factorization theorem. I mean, get a number>1 from user and print all the unique factorization with a counter.

for ex, for 100 the output should be

2 2

5 2

since 100=2*2*5*5

and for 23 the output should be

23

if the input is 6, the output will be

2
3

and last example, for 8112, output should be

2 4
3
13 2

so far, I implement a code which gives the first column and correct for prime numbers. however I did not succeed to count when counter >1 to print the second column.

My code is below:

int n = scanner.nextInt();
    int num = 2;
    while (num <= n) {
        int i = 2;
        boolean isPrime = true;
        while (i < num && isPrime) {
            if (num % i == 0) {
                isPrime = false;
            }
            i++;
        }
        if (isPrime) {
            int counter = 1;
            if (n % num == 0) {
                System.out.println(num);
            }
        }
        num++;
    }

Any ideas what I am missing?


回答1:


Your counter hasn't been implemented yet.

int n = scanner.nextInt();
int num = 2;
while (num <= n) {
    int i = 2;
    boolean isPrime = true;
    while (i < num && isPrime) {
        if (num % i == 0) {
            isPrime = false;
        }
        i++;
    }
    if (isPrime) {
        int counter = 0;
        while (n >= num && n % num == 0) {
            counter++;
            n /= num;
        }
        if (counter == 1) {
            System.out.println(num);
        }
        else if (counter > 1) {
            System.out.println(num + " " + counter);
        }
    }
    num++;
}



回答2:


After finding the number, you must continue to find the counter of that. Below is my solution.

            int ounter = 0;
            if (n % num == 0) {
                System.out.print(num);
                int n1 = n;
                while(n1%num == 0) {
                    ounter ++;
                    n1 = n1/num;
                }
                if(ounter != 1) {
                    System.out.println(" "+ounter);
                }
            }


来源:https://stackoverflow.com/questions/53059927/unique-factorization-with-counter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!