编写一个具有2个线程的程序,一个线程用于计算n以内的素数,一个线程用于求1!+2!+…+m!。
1个回答
展开全部
亲测 输出结果为
public class TwoThread {
60以内的素数有[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,]
6以内的阶乘之和为:873
一下为源代码
public class TwoThread {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ThreadA ta = new ThreadA(60);
ta.start();
ThreadB tb = new ThreadB(6);
tb.start();
}
}
class ThreadA extends Thread {
public StringBuilder printStr = new StringBuilder();
private int num;
public ThreadA(int num) {
this.num = num;
}
@Override
public void run() {
printStr.append(num + "以内的素数有[");
for (int i = 2; i <= num; i++) {// 循环1 循环判断该数是否为质数 因为1不是质数所以从2开始循环
boolean flag = true;
for (int m = 2; m <= (i - 1); m++) {// 循环2 因为1和本身肯定能被整除 所以从2开始至当前数-1循环
if (i % m == 0) {// 如果循环2循环到有数能被当前数整除 则跳出循环2 并且当前数不是质数 所以设置flag变量值为false
flag = false;
break;
}
}
if(flag) {
printStr.append(i).append(",");
}
}
printStr.append("]");
System.out.println(printStr);
}
}
class ThreadB extends Thread {
private int num;
public ThreadB(int num) {
this.num = num;
}
@Override
public void run() {
int sum = 0;
for(int i = 1; i <= num; i++) {
int sumB = 1;
for(int m = 1; m <= i; m++) {
sumB = sumB * m;
}
sum += sumB;
}
System.out.println(num + "以内的阶乘之和为:" + sum);
}
}
public class TwoThread {
60以内的素数有[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,]
6以内的阶乘之和为:873
一下为源代码
public class TwoThread {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ThreadA ta = new ThreadA(60);
ta.start();
ThreadB tb = new ThreadB(6);
tb.start();
}
}
class ThreadA extends Thread {
public StringBuilder printStr = new StringBuilder();
private int num;
public ThreadA(int num) {
this.num = num;
}
@Override
public void run() {
printStr.append(num + "以内的素数有[");
for (int i = 2; i <= num; i++) {// 循环1 循环判断该数是否为质数 因为1不是质数所以从2开始循环
boolean flag = true;
for (int m = 2; m <= (i - 1); m++) {// 循环2 因为1和本身肯定能被整除 所以从2开始至当前数-1循环
if (i % m == 0) {// 如果循环2循环到有数能被当前数整除 则跳出循环2 并且当前数不是质数 所以设置flag变量值为false
flag = false;
break;
}
}
if(flag) {
printStr.append(i).append(",");
}
}
printStr.append("]");
System.out.println(printStr);
}
}
class ThreadB extends Thread {
private int num;
public ThreadB(int num) {
this.num = num;
}
@Override
public void run() {
int sum = 0;
for(int i = 1; i <= num; i++) {
int sumB = 1;
for(int m = 1; m <= i; m++) {
sumB = sumB * m;
}
sum += sumB;
}
System.out.println(num + "以内的阶乘之和为:" + sum);
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询