我正在嘗試編寫一個程序,它可以將輸出作爲給定數字的素數分解。但是,我的代碼作爲"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