如何在随后打印的素数之间添加“ x”,而在最后打印的素数后没有多余的“ x”?

时间:2019-10-05 20:23:03

标签: java

我正在执行素数分解代码,并且尝试在用户输入的数字的每个显示的素数之间打印“ x”。但是,我似乎无法弄清楚如何制作它,以免在最后显示的素数之后出现一个额外的“ x”。

我已经尝试在print语句中的“ x”之后连接mod,并且尝试考虑将if语句用于(startInt%mod == 0),但是我不太确定其他情况声明就是为此。

    System.out.println("Enter an integer to be factored:");
    int startInt = userInput.nextInt();

    if(startInt % 2 == 0 || startInt % 3 == 0 || startInt % 5 == 0 || startInt % 7 == 0 || startInt % 11 == 0 || startInt % 13 == 0)
    {
        for(int mod = 2; mod <= startInt; mod++)
        {
            while(startInt%mod == 0)
            {
                startInt /= mod;
                System.out.print(mod+" x ");
            }
        }
    }

    else
    {
        System.out.println(startInt+" = "+startInt);
        System.out.println(startInt+" is a prime number.");
    }

我希望784784的输出为2 x 2 x 2 x 2 x 7 x 7 x 7 x 11 x 13,但实际输出为2 x 2 x 2 x 2 x 2 x 7 x 7 x 7 x 11 x 13 x。

3 个答案:

答案 0 :(得分:0)

检查此示例(我将其改编为Javascript,但固定线是两种语言的示例):

...
PROJECT_PATH = dirname(dirname(dirname(__file__)))
MEDIA_ROOT = os.path.join(PROJECT_PATH, 'htdocs/media')
STATIC_ROOT = os.path.join(PROJECT_PATH, 'htdocs/static')
...

您必须避免在上一个循环中添加“ x”:

result + = mod +(mod

答案 1 :(得分:0)

一个非常简单的示例,使用附加变量first知道(是否为第一次迭代)。在此示例中,i > 0可能已经被用来知道,它不是第一次迭代,但是如果不与索引循环(例如,while (!collection.isEmpty())),使用变量也可以。

public class Demo {
    public static void main(String[] args) {
        boolean first = true;
        for (int i = 0; i < 5; i++) {
            if (!first) {
                System.out.print(" x ");
            }
            System.out.print(i);
            first = false;  // not first after this iteration
        }
    }
}

答案 2 :(得分:0)

为简化您的问题,请分开关注-首先构建主要因素列表,然后打印列表

List<String> primeFactors = new ArrayList<>();

// your algorithm, which will instead add prime factors to the above list

String result = String.join(" x ", primeFactors);

String::join不幸的是仅接受字符串列表,如果您想加入整数列表,可以查看this question