厄拉多塞篩演算法
阿新 • • 發佈:2018-12-20
package abc; public class ch221 { public static long sh221(int n){ <span style="white-space:pre"> </span> int[] a=new int[n]; <span style="white-space:pre"> </span> int sum=0; <span style="white-space:pre"> </span> for(int i=0;i<a.length;i++){ <span style="white-space:pre"> </span> a[i]=i+1; <span style="white-space:pre"> </span> } <span style="white-space:pre"> </span> for(int i=(int) Math.sqrt(n);i>=2;i--){ <span style="white-space:pre"> </span> for(int j=i+1;j<n;j++){ <span style="white-space:pre"> </span> if((a[j]%i)==0){ <span style="white-space:pre"> </span> a[j]=0; <span style="white-space:pre"> </span> } <span style="white-space:pre"> </span> } <span style="white-space:pre"> </span> } <span style="white-space:pre"> </span> for(int i=0;i<a.length;i++){ <span style="white-space:pre"> </span> if(a[i]!=0){ <span style="white-space:pre"> </span> System.out.println(a[i]); <span style="white-space:pre"> </span> sum+=a[i]; <span style="white-space:pre"> </span> } <span style="white-space:pre"> </span> <span style="white-space:pre"> </span> } <span style="white-space:pre"> </span> return sum; } public static void main(String[] args) { <span style="white-space:pre"> </span>long s=sh221(200); <span style="white-space:pre"> </span>System.out.println(s); <span style="white-space:pre"> </span> } }