编程题:
(1)编写应用程序求1!+2!+3!+4!+5!+6!+7!+8!+9!+10!。
package a;
public class 练习1 {
public static void main(String[] args){
int sum=0,n=1;
for(int i=1;i<=10;i++)
{
for(int j=1;j<=i;j++){
n=n*j;
}
sum=sum+n;
n=1;
}
System.out.println(sum);
}
}
(2)编写一盒应用程序求100以内的全部素数。
package a;
public class 练习2 {
public static void main(String[] args) {
int j;
for (int i = 2; i <= 100; i++) {
for (j = 2; j < Math.sqrt(i); j++) {
if (i % j == 0) {
break;
}
}
if (j > Math.sqrt(i)) {
System.out.println(i);
}
}
}
}
(3)分别用do-while和for循环计算1+1/2!+1/3!+1/4+···的前20项和。
do-while循环:
package a;
public class 练习3 {
public static void main(String[] args) {
double i = 1, sum = 0;
do {
double a = 1;
for (int j = 1; j <= i; j++) {
a = a * j;
}
sum += 1 / a;
a = 1;
i++;
} while (i <= 20);
System.out.println(sum);
}
}
for循环:
package a;
public class 练习3 {
public static void main(String[] args) {
double a = 1, sum = 0;
for (double i = 1; i <= 20; i++) {
for (double j = 1; j <= i; j++) {
a = a * j;
}
sum = sum + 1 / a;
a = 1;
}
System.out.println(sum);
}
}
(4)一个数如果恰好等于它的因子之和,这个数就称为完数。编写应用程序求1000之内的所有完数。
package a;
public class 练习4 {
public static void main(String[] args) {
for (int i = 1; i <= 1000; i++) {
int sum = 0;
for (int j = 1; j < i; j++) {
if (i % j == 0) {
sum += j;
}
}
if (sum == i) {
System.out.println(i);
}
}
}
}
(5)编写应用程序,使用for循环语句计算8+88+888+···前10项之和。
package a;
public class 练习5 {
public static void main(String[] args) {
long sum = 0, a = 8;
for (int i = 1; i <= 10; i++) {
sum = sum + a;
a = a * 10 + 8;
// System.out.println(a);
}
System.out.println(sum);
}
}
(6)编写应用程序,输出满足1+2+3+···+n<8888的最大正整数n。
package a;
public class 练习 {
public static void main(String[] args) {
int sum = 0;
for (int i = 1; sum < 8888; i++) {
sum = sum + i;
if (sum > 8888) {
System.out.println(i - 1);
}
}
}
}