JAVA 中的主要因素
Prime Factors in JAVA
我正在尝试编写一个程序,将输出作为给定数字的质数分解。但是,我的代码作为 "2**2**2**2**2**5**7**7**11*"
的输出给出了正确的答案,但我希望它的特定输出为 "(p1**n1)(p2**n2)...(pk**nk)"
。这是我的代码:
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));
}
}
您几乎明白了,与其一次计算一个因素,不如计算同一个因素的所有因素并计算它们:
public static String factors(int n)
{
String ans = "";
int count = 0;
for (int i = 2; i <= n; i++)
{
// Reset the counter
count = 0;
/*
* Instead of only processing on factor, we process them all and
* count them
*/
while (n % i == 0)
{
count++;
n = n / i;
}
// If we have at least processed one add it to the string
if (count == 1)
{
ans += "(" + i + ")";
} else if (count > 0)
{
ans += "(" + i + "**" + count + ")";
}
}
return ans;
}
由于您经常在循环中操作字符串,因此您应该使用 StringBuilder
我正在尝试编写一个程序,将输出作为给定数字的质数分解。但是,我的代码作为 "2**2**2**2**2**5**7**7**11*"
的输出给出了正确的答案,但我希望它的特定输出为 "(p1**n1)(p2**n2)...(pk**nk)"
。这是我的代码:
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));
}
}
您几乎明白了,与其一次计算一个因素,不如计算同一个因素的所有因素并计算它们:
public static String factors(int n)
{
String ans = "";
int count = 0;
for (int i = 2; i <= n; i++)
{
// Reset the counter
count = 0;
/*
* Instead of only processing on factor, we process them all and
* count them
*/
while (n % i == 0)
{
count++;
n = n / i;
}
// If we have at least processed one add it to the string
if (count == 1)
{
ans += "(" + i + ")";
} else if (count > 0)
{
ans += "(" + i + "**" + count + ")";
}
}
return ans;
}
由于您经常在循环中操作字符串,因此您应该使用 StringBuilder