嗨大家好,我有这个代码的问题是mersenne primes的数量应该是4但它输出8.我知道这是因为1到1000之间的Mersenne素数是3,7,31,和127但它也输出15,63,255和511.我不知道为什么。还有一种方法可以输出每100个数字的Primes数量吗?谢谢
public static void main(String[] args) {
System.out.println("Prime numbers between 1 and 1000 are\n");
String message = "";
String message2 = "";
// loop numbers from 1 to 1,000, printing only the primes
int counter2 = 0;
int counter = 0;
for( int number s= 2; number <= 1000; number ++){
if(isPrime(number)) {
counter++;
if(counter % 10 == 0) {
System.out.println(number);
}
else
System.out.print(number + " ");
}
}
for(int number2 = 2; number2 <= 1000; number2 ++){
if(isMersenne(number2)){
counter2++;
System.out.print(number2 + "*");
}
}
System.out.print( "\n\n The number of primes between 1 and 1000 are " + counter);
System.out.print( "\n The number of Mersennes is " + counter2);
}
public static boolean isPrime( int number ){
// initialize the boolean variable prime to true
boolean isPrime = true;
for(int divisor = 2; divisor <= number /2; divisor++) {
if(number % divisor == 0) {
isPrime = false;
}
}
return isPrime;
}
public static boolean isMersenne(int number){
// declare and initialize variable powTwo to 2
int powTwo = 2;
boolean mersenne = false;
while(powTwo <= number){
powTwo *= 2;
if(powTwo - number == 1)
// if the prime is one less than a power of 2, return true
mersenne = true;
}
return mersenne;
} // end method isMersenne
}
这是我程序的输出
Prime numbers between 1 and 1000 are
2 3 5 7 11 13 17 19 23 29
31 37 41 43 47 53 59 61 67 71
73 79 83 89 97 101 103 107 109 113
127 131 137 139 149 151 157 163 167 173
179 181 191 193 197 199 211 223 227 229
233 239 241 251 257 263 269 271 277 281
283 293 307 311 313 317 331 337 347 349
353 359 367 373 379 383 389 397 401 409
419 421 431 433 439 443 449 457 461 463
467 479 487 491 499 503 509 521 523 541
547 557 563 569 571 577 587 593 599 601
607 613 617 619 631 641 643 647 653 659
661 673 677 683 691 701 709 719 727 733
739 743 751 757 761 769 773 787 797 809
811 821 823 827 829 839 853 857 859 863
877 881 883 887 907 911 919 929 937 941
947 953 967 971 977 983 991 997 3*7*15*31*63*127*255*511*
The number of primes between 1 and 1000 are 168
The number of Mersennes is 8
答案 0 :(得分:2)
你的问题是isMersenne
只是检查数字是否小于2的幂。它还没有检查它是否是一个主要因素。
您需要更改isMersenne
方法,以便在检查该数字是否小于2的幂时调用isPrime
。如果isPrime
返回false,则isMersenne
也应返回false。