首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >利用指数的分解环

利用指数的分解环
EN

Stack Overflow用户
提问于 2014-04-06 01:22:36
回答 1查看 218关注 0票数 0

这个程序基本上是用指数来计算和打印的。它正在接近正确的答案,但它继续循环,不打印在同一条线上。例如,对于600,它应该打印2^3*3*5^2,但继续打印2^3 (新行) 3^1 (新行) 5^2,重复。

更新:修复了重复问题,现在打印2^ 3 ^1 ^ 5^2,现在只需要正确打印。

代码语言:javascript
复制
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");
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-04-06 01:33:59

在循环中需要一个标志来确定它是否是第一个因素

代码语言:javascript
复制
    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);
    }
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22888903

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档