我正在尝试编写一个程序,它可以将输出作为给定数字的素数分解。但是,我的代码作为"2**2**2**2**2**5**7**7**11*"
的输出提供了正确的答案,但我希望它的具体输出为"(p1**n1)(p2**n2)...(pk**nk)"
。这里是我的代码:JAVA中的素数因子
public class PrimeDecomp
{
public static String factors(int n)
{
String ans = "";
for (int i = 2; i <= n; i++)
{
if (n % i == 0)
{
// checks if i is a divisor of num
ans += i + "**";
// writes i in prime factorization
n = n/i;
// since it is written down, num=num/i
i--;
// just in case their are multiple factors of same number.
// For example, 12=2*2*3
}
}
return (ans.substring(0, ans.length() - 1));
}
public static void main(String[] args)
{
System.out.println(PrimeDecomp.factors(86240));
}
}
/*公共类PrimeDecomp { \t \t公共静态字符串因素(INT N){ \t \t \t \t String ans =“”; \t \t的for(int i = 2; I <= N;我++){ \t \t如果(N%I == 0){//检查是否i是NUM的除数 \t \t ANS + = I +“** “; //在素因式分解中写入i \t \t n = n/i; //因为它被写下来,所以num = num/i \t \t i--; //以防万一他们是多个相同数字的因素。例如,12 = 2 * 2 * 3 \t \t} \t \t} \t \t回报(ans.substring(0,ans.length() - 1)); } \t public static void main(String [] args){ \t \t System.out.println(PrimeDecomp.factors(86240)); \t} } */ –
您可能已经注意到注释并没有很好地格式化代码。你需要编辑你的问题并在那里添加你的代码。 – azurefrog
请确保你[请正确格式化](http://stackoverflow.com/editing-help)。 – tnw