[英]What is the error in my Largest Prime Number program?
public class LargestPrimeFactor {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int cases = scan.nextInt();
int num = 0, temp = 0;
while(cases!=0) {
num = scan.nextInt();
for(int i=2; i<=num; i++)
if(num%i==0) {
if(isPrime(i)) {
if(temp<i)
temp = i; //to always have the largest factor
}
num/=i; // to reduce the iterations for a large number.
}
System.out.println(temp);
cases--;
}
}
public static boolean isPrime(int num) {
if ( num > 2 && num%2 == 0 )
return false;
int top = (int)Math.sqrt(num) + 1;
for(int i = 3; i < top; i+=2)
if(num % i == 0)
return false;
return true;
}
}
This code computes the largest prime factor of a number.此代码计算一个数的最大质因数。 This gives an error 5/6 times from an Online Judge.
这会导致在线裁判错误 5/6 次。 I can't figure out the exception or error.
我无法弄清楚异常或错误。 Please help...
请帮忙...
You should reset temp to 0 for each case.对于每种情况,您都应该将 temp 重置为 0。 Example input:
示例输入:
2 7 4
Expected output:预期输出:
7
2
Actual output实际产量
7
7
Hope it helps.希望能帮助到你。
Such errors are easier to make when you declare your variables earlier than you need them.当您在需要之前声明变量时,更容易产生此类错误。 Instead of
代替
int num = 0, temp = 0;
while(cases!=0) {
num = scan.nextInt();
try尝试
while (cases != 0) {
int num = scan.nextInt();
int temp = 0;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.