统计信息

  • 访问数:14069
  • 博客数:143
  • 建立时间:2008-01-05
  • 更新时间:2008-10-15
我叫王超然,是一名电脑爱好者,现在在新加坡留学上高一.我立志成为一名电脑人才,愿意在这里与大家一同分享我玩转电脑的心得.O-level华文考了A-One哈哈!

P4Q4

2008-02-13 15:29:48

天气: 晴朗 心情: 高兴

/*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++;
    }
  }
 
}
 

 


加入收藏 编辑 审核

TAG: computing

我来说两句

OPEN

Powered by X-Space 1.2 © 2001-2006 Comsenz Technology Ltd