我写了一个程序来确定给定数字的因子。首先,它当然应该检查数字是否是素数。这是有效的,但如果数字是一个正方形数字,它会将其识别为素数...
public class factors {
public static void main (String [] args) {
System.out.println("Enter the number you need factors of");
int base = Kon.readInt();
for (int i = 2; i < base; i++) {
int a = base % i;
if (a == 0) {
break;
}
else {
System.out.println(base+" is a prime number, so it has no factors");
break;
}
}
for (int i = 3; i < base; i++) {
int res = base % i;
if (res == 0) {
int fac = base / i;
System.out.println(i+" and "+fac+" are factors of "+base);
}
}
}
}
所以,如果我输入64,它表示这是一个素数,但后来告诉我8和8是下一行64的因子
有谁知道问题可能是什么?
答案 0 :(得分:0)
问题在于
if (a==0) {
break;
} else {
System.out.println(base+" is a prime number, so it has no factors");
break;
}
将在i
无法被 for (int i=2;i<base;i++) {
int a=base%i;
if (a==0) {
break;
}
else {
System.out.println(base+" is a prime number, so it has no factors");
break;
} // end of if-else
}
整除的情况下输出一个数字不是素数,所以在决定它不是素数之前,你必须首先完全循环它。
所以你要改变:
prime = true;
for (int i=2;i<base;i++) {
int a=base%i;
if (a==0) {
prime = false;
break;
}
}
if (prime){
System.out.println(base+" is a prime number, so it has no factors");
} // not a prime
成:
{{1}}
答案 1 :(得分:0)
问题是你打印它是你的循环中的素数 ,所以只要至少有一个值{{},就假装一个数字是素数{1}} i
为base%i
。{/ p>
您应检查0
的否值是否正确。例如,你可以这样做:
i
答案 2 :(得分:0)
if (a == 0) {
break;
}
else {
System.out.println(base+" is a prime number, so it has no factors");
break;
}
无论如何,你都会在第一个增量上突破循环。即使您从break;
块移除了else
,您仍然会过早地显示该数字是否为素数。在所有迭代完成后,您需要确定。
因此,请考虑使用boolean
变量来跟踪数字中是否至少包含一个因素:
boolean isPrime = true; // true unless proven otherwise
for (int i = 2; i < base; i++) {
int a = base % i;
if (a == 0) {
isPrime = false; // has factor so it's not prime
break;
}
}
if (isPrime) {
System.out.println(base + " is a prime number, so it has no factors");
} else {
System.out.println(base + " is a composite number: "); // say it's not prime
// then display the factors
for (int i = 3; i < base; i++) {
int res = base % i;
if (res == 0) {
int fac = base / i;
System.out.println(i + " and " + fac + " are factors of " + base);
}
}
}