简体   繁体   English

使用指数的因式分解循环

[英]Factorization loop using exponents

This program basically factors and prints using exponents. 该程序基本上使用指数进行因子分解和打印。 It is getting close to the right answer, but it continues looping and doesn't print them on the same line. 它接近正确的答案,但它会继续循环播放,并且不会将它们打印在同一行上。 For example, for 600 it should print 2^3*3*5^2, but continues to print 2^3 (new line) 3^1 (new line) 5^2, repeated. 例如,对于600,它应打印2 ^ 3 * 3 * 5 ^ 2,但继续打印2 ^ 3(新行)3 ^ 1(新行)5 ^ 2,重复进行。

UPDATE: fixed the repeating problem by fixing the sentinal, now prints 2^3 3^1 5^2, just need t to print correctly now. 更新:通过修复哨兵解决了重复性问题,现在打印2 ^ 3 3 ^ 1 5 ^ 2,现在只需正确打印即可。

import java.util.Scanner;
class Factoring {
    int n;
    void setN(int u) {
        n = u;
    }

    int getN() {
        return n;
    }

    void factorize() {
        int cnt;

        for (int i = 2; i <= n; i++) {
            cnt = 0;
            while (n%i == 0) {
                cnt++;
                n /= i;
            }
            if (cnt == 0)
                continue;
            System.out.println(i + "^" + cnt);
        }
    }
}

public class Hw10 {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        Factoring myF = new Factoring();

        int u;

        System.out.print("Enter a number(1 or less to stop)");
        u = in.nextInt();
        while (u > 1) {
            myF.setN(u);
            myF.factorize();

            System.out.print("Enter a number(1 or less to stop)");
            u = in.nextInt();
        }
        System.out.print("bye");
    }
}

You need a flag inside the loop to determine if it's the first factor eg 您需要在循环内部添加一个标志,以确定是否是第一个因素,例如

    int cnt;
    boolean isFirstFactor = true;

    for (int i = 2; i <= n; i++) {
        cnt = 0;
        while (n%i == 0) {
            cnt++;
            n /= i;
        }
        if (cnt == 0)
            continue;
        if (isFirstFactor)
            isFirstFactor = false;
        else
            System.out.print(" * ");
        System.out.print(i + "^" + cnt);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM