带计数器的独特分解 [英] Unique factorization with counter

查看:115
本文介绍了带计数器的独特分解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在JAVA中构建一个使用Unique factorization定理的程序。
我的意思是,从用户那里获得一个> 1的数字并用计数器打印所有独特的因子分解。

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.

对于ex,对于100,输出应该是

for ex, for 100 the output should be

2 2

5 2

因为100 = 2 * 2 * 5 * 5

since 100=2*2*5*5

并且对于23,输出应为

and for 23 the output should be

23

如果输入为6,输出为

2
3

和最后一个例子,对于8112,输出应该是

and last example, for 8112, output should be

2 4
3
13 2

到目前为止,我实施了给出第一列并对素数进行校正的代码。但是,当计数器> 1打印第二列时,我没有成功计算。

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.

我的代码如下:

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

我缺少什么想法?

推荐答案

您的计数器尚未实施。

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

这篇关于带计数器的独特分解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆