使用java语言实现的一个案例,模拟一层for循环相当于平方运算,二层for循环相当于立方运算,三层for循环相当于4次方运算,以此类推。可以看出每层for偱环运算,运算次数是按指数次方增加的。指数运算对于计算机来说,相当于无解,一般三层以上的for循环是不可取的。计算机编程,其实就是把指数运算拆解成多项式运算。
Main.java文件:
import java.util.*;
public class Main {
private int param = 0;
public static void main(String [] args) {
Main s = new Main();
if(args.length == 0){
// 不带参数运行的数据
s.setParam(4); // 设置要运算的数
}else{
// 带参数运行的数据
System.out.println("=============================n");
System.out.println("你输入了" + args.length + "个参数,但第一个参数有效!n");
System.out.print("参数为:");
for(int l = 0; l < args.length; l++){
System.out.print(args[l] + " ");
}
System.out.println("nn=============================n");
if(Integer.valueOf(args[0]) > 99){
System.out.println("输入的参数过大,参数已禁止写入!");
}else{
s.setParam(Integer.valueOf(args[0]));
// 输出结果
// 平方运算
s.print(s.compute2 ());
// 立方运算
s.print(s.compute3 ());
// 4次方运算
s.print(s.compute4 ());
}
}
}
public int getParam(){
return this.param;
}
public void setParam(int record){
this.param = record;
}
// X²
public int [] compute2 (){
int [] total = new int [] {0, 0, 2};
// 一层循环相当于平方
for(int i = 0; i < this.param; i++){
total[0] = total[0] + this.param;
total[1]++;
}
return total;
}
// X³
public int [] compute3 (){
int [] total = new int [] {0, 0, 3};
// 二层循环相当于立方
for(int i = 0; i < this.param; i++){
for(int j = 0; j < this.param; j++){
total[0] = total[0] + this.param;
total[1]++;
}
}
return total;
}
// X⁴
public int [] compute4 (){
int [] total = new int [] {0, 0, 4};
// 三层循环相当于4次方
for(int i = 0; i < this.param; i++){
for(int j = 0; j < this.param; j++){
for(int k = 0; k < this.param; k++){
total[0] = total[0] + this.param;
total[1]++;
}
}
}
return total;
}
// 显示输出
public void print(int [] printParam){
System.out.println(printParam[2] + "次方运算共运行了" + printParam[1] + "次");
System.out.println("结果:" + printParam[0] + "n");
}
}
运行后的效果:
2次方运算共运行了35次,相当于X¹次运算;
3次方运算共运行了1225次,相当于X²次运算;
4次方运算共运行了42875次,相当于X³次运算。
可以看出,每增加一层for循环,相当于增加了一级指数运算量;当数据量比较大时,计算会变得无解。
暑期编程PK赛 得CSDN机械键盘等精美礼品!



