新闻正文

发一个求质数的简单的实现的方法

来源:JAVA天堂  JAVA学习者  2007-8-7 01:57:51 网友评论 0 条 字体:[ ] ~我要投稿!
我爱南开站 (Mon Apr 5 13:48:04 2004)
转信站: SJTU!netnews.sdu.edu.cn!news.happynet.org!NanKai
public class MorePrimes
{
public static void main(String[] args)
{
long[] primes = new long[20]; // Array to store primes
primes[0] = 2; // Seed the first prime
primes[1] = 3; // and the second
int count = 2; // Count of primes found - up to now,
// which is also the array index
long number = 5; // Next integer to be tested
outer:
for( ; count < primes.length; number += 2)
{
// The maximum divisor we need to try is square root of number
long limit = (long)Math.ceil(Math.sqrt((double)number));
// Divide by all the primes we have up to limit
for(int i = 1; i < count && primes[i] <= limit; i++)
if(number%primes[i] == 0) // Is it an exact divisor?
continue outer; // yes, try the next number
primes[count++] = number; // We got one!
}
for(int i=0; i < primes.length; i++)
System.out.println(primes[i]); // Output all the primes
}
}
【 在 anglehurt (像林冲那样唱歌) 的大作中提到: 】
: public class Primes {
: public static void main(String args[]) {
: int maxValue = 50; // The maximum value to be checked.
: // Check all values from 2 to maxValue:
: OuterLoop:
: for(int i=2 ; i<=maxValue ; i++) {
: // Try dividing by all integers from 2 to square root of i:
: for(int j=2 ; j<=Math.sqrt(i) ; j++) {
: if(i%j == 0) // This is true if j divides exactly
: continue OuterLoop; // so exit the loop.
: .................(以下省略)

被神仙抓去以后,第一天,他们打我,我没有说,第二天,他们
打我,我还是没有说,第三天,他们送来一个漂亮mm,我说了,
第四天,我还想说,可是他们把我砍了……



收藏到ViVi   收藏此页到365Key
上一篇: 发一个求质数的简单的实现的方法
下一篇: JSP能不能实现一个文件的多点同时上传
用户名:新注册) 密码: 匿名评论 [所有评论]
评论内容:不能超过250字,需审核后才会公布,请自觉遵守互联网相关政策法规。
本栏搜索
  • Google
   网站首页 -  网站地图 -  技术学习 -  网站投稿 -  帮助中心
Copyright 2003-2008 www.javah.net All Rights Reserved
2008 如果你喜欢本站 请收藏本站 并推荐给你的朋友一起分享