JAVA质数 JAVA及PYTHON质数计算代码对比解析
天涯未抵 人气:1Java 实现
class PrimeNumber{ public static void main(String[] args) { long start=System.currentTimeMillis(); int count=0; label:for(int i=1;i<=100000;i++){ for (int j=2;j<=Math.sqrt(i);j++) { if(i%j==0){ continue label; //返回外层循环 } } count++; // System.out.println(i); } long end=System.currentTimeMillis(); System.out.println("count"+count); //9593 System.out.println("time(ms)"+(end-start)); //time 14ms } }
Python 实现
import time import math def main(): start=time.time() count=0 for i in range(1,100001): isFlag=True for j in range(int(math.sqrt(i)),1,-1): if i%j==0: isFlag=False break if (isFlag): count+=1 end=time.time() print('count',count) //9593 print('time(ms)',(end-start)*1000) //697.28684425354ms if __name__ == '__main__': main()
结论
Java实现质数计算效率更高,循环处理方式更灵活,Python可读性高,各有各的特点。
加载全部内容