我叫王超然,是一名电脑爱好者,现在在新加坡留学上高一.我立志成为一名电脑人才,愿意在这里与大家一同分享我玩转电脑的心得.O-level华文考了A-One哈哈!
天气: 晴朗
心情: 高兴
/*P4Q4
Name:Wang Chaoran
Description:4 (Printing prime numbers between 2 and 1000)
Modify Listing 4.11 to print all the prime numbers between 2 and 1000, inclusively. Display eight prime numbers per line.
*/
public class P4Q4{
/** Main method */
public static void main(String[] args) {
final int NUMBER_OF_PRIMES_PER_LINE = 8; // Display 10 per line
int count = 0; // Count the number of prime numbers
int number = 2; // A number to be tested for primeness
System.out.print("prime numbers between 2 and 1000 \n");
// Repeatedly find prime numbers
while (number<1000) {
// Assume the number is prime
boolean isPrime = true; // Is the current number prime?
// Test if number is prime
for (int divisor = 2; divisor <= number / 2 ;divisor++) {
if (number % divisor == 0) // the number is not prime
{isPrime = false; // Set isPrime to false
break;// Exit the for loop
}
}
// Print the prime number and increase the count
if (isPrime) {
count++; // Increase the count
if (count % NUMBER_OF_PRIMES_PER_LINE == 0) {
// Print the number and advance to the new line
System.out.println(number);
}
else{
System.out.printf("%-4d",number);
}
}
// Check if the next number is prime
number++;
}
}
}
导入论坛查看(46)回复(0)引用(0)好评(0) 差评(0)
加入收藏
编辑
审核
TAG:
computing