计算1+1/2!+1/4!+…前10项和
package illustration;
public class factorial {
public static void main(String[] args) {
//计算1+1/2!+1/4!+...前10项和
double sum = 0, item = 1;
int i = 1;
while(i<=10){
sum = sum +item;
i = i+1;
item = item*(1.0/i);
}
System.out.println("sum="+sum);
}
}
计算100以内的奇数之和
求出100以内的素数
package illustration;
public class primeSum {
public static void main(String[] args) {
//计算100以内的奇数之和
int sum=0;
int i,j;
for(i=1;i<=100;i++){
if(i%2==0){ //计算1+3+5+7+9
continue;
}
sum = sum+i;
}
System.out.println("100以内的奇数之和为: "+sum);
//求100以内的素数
System.out.println("100以内的素数为:");
for (j=2;j<=100;j++){
for(i=2;i<=j/2;i++){
if(j%i==0){
break;
}
}
if(i>j/2){
System.out.print(j+" ");
}
}
}
}