统计信息

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

P6Q06

2008-04-14 17:55:31

天气: 晴朗 心情: 高兴

/*Filename:P6Q06
 * Name:Wang Chaoran
Description:6 (Revising Listing 4.11, PrimeNumber.java)
Listing 4.11 determines whether a number n is prime by checking whether
2, 3, 4, 5, 6, ..., n/2 is a divisor. If a divisor is found, n is not prime.
A more efficient approach to determine whether n is prime is to check whether any
of the prime numbers less than or equal to square root  can divide n evenly. If not,
n is prime. Rewrite Listing 4.11 to display the first fifty prime numbers using this approach.
You need to use an array to store the prime numbers and later use them to check whether they are
possible divisors for n.
*/
public class P6Q06{
  public static void main(String[] args){
    int number = 2;
    int count = 0;
    int[] prime = new int[800];
    while(count<800){
      if(isPrime(number)){
        prime[count]=number;
        count++;
      }
      number++;
    }
    for(int i=0;i<prime.length;i++)
    System.out.print(prime[i]+" ");
   
  }
  static boolean isPrime(int number){
    for(int i =2;i<=Math.sqrt(number);i++){
      if(number%i==0)
        return false;
    }
    return true;
  }
  }

/*Filename:P6Q06
 * Name:Wang Chaoran
Description:6 (Revising Listing 4.11, PrimeNumber.java)
Listing 4.11 determines whether a number n is prime by checking whether
2, 3, 4, 5, 6, ..., n/2 is a divisor. If a divisor is found, n is not prime.
A more efficient approach to determine whether n is prime is to check whether any
of the prime numbers less than or equal to square root  can divide n evenly. If not,
n is prime. Rewrite Listing 4.11 to display the first fifty prime numbers using this approach.
You need to use an array to store the prime numbers and later use them to check whether they are
possible divisors for n.
*/
class P6Q06{
  public static void main(String[] args){
    int[] prime = new int[50];
    int number =2;
    int count =0;
    while(count<50){
      if(isPrime(number,count,prime))
      {
        prime[count]=number;    
        count++;
      }
     number++;
    }
    for(int i=0;i<prime.length;i++){
    System.out.print(prime[i]+" ");
    }
  }
  static boolean isPrime(int number,int count,int[] prime){
      for(int i =0;i<count;i++)
        if(number%prime[i]==0)
          return false;
    return true;  
  }
  }


加入收藏 编辑 审核

TAG: computing

我来说两句

OPEN

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