博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
计算质数和回文数的小程序
阅读量:2239 次
发布时间:2019-05-09

本文共 2053 字,大约阅读时间需要 6 分钟。

Ruby 代码如下
 
1:  def isZhishu?(num)
2:      count = 2
3:      while count < num do
4:          return false if ( num % count ) == 0
5:          count = count + 1
6:      end
7:   
8:      return true
9:  end
10:   
11:  def isHuiwen?(num)
12:      s = num.to_s.reverse.to_i
13:      return true if num == s
14:   
15:      return false
16:  end
17:   
18:  count = 0
19:  10000.times{ |i|
20:      i = i + 1
21:      if isZhishu?(i) && isHuiwen?(i) then
22:          printf "%4d", i
23:          print "\n"
24:          count = count + 1
25:      end
26:  }
27:  print "\n\nTotal:#{count}"

 

上面这个方法非常笨重,时间复杂度是 O(n^2),可以进行一些优化。根据 sdpfoue 的建议,做了优化。

首先就是可以只对大于3的奇数进行检查,因为偶数肯定可以被2整除,所以不需要考虑。

另外循环相除的时候,可以只除以质数,这样也能够减少不少步骤。但是会增加空间的消耗,就是所谓的用空间换时间。

具体代码如下:

1:  def isZhishu?(num, arrZhishu)
2:      return true if num == 1 || num == 2
3:      count = 2
4:   
5:      if( arrZhishu.empty? )then
6:          #count = 2
7:          while count < num do
8:              return false if ( num % count ) == 0
9:              if( count >= 11 ) then
10:                  count = count + 2 # Only judge even numbers
11:              else
12:                  count = count + 1
13:              end
14:          end
15:   
16:          return true
17:      else
18:          arrZhishu.each{|value|
19:              next if value == 1
20:              return false if ( num % value ) == 0
21:          }
22:          return true
23:      end
24:  end
25:   
26:  def isHuiwen?(num)
27:      s = num.to_s.reverse.to_i
28:      return true if num == s
29:   
30:      return false
31:  end
32:   
33:  count = 0
34:  arrZhishu = Array.new
35:  i = 0
36:  while i < 10000000 do
37:      if i >= 11 then
38:          i = i + 2
39:      else
40:          i = i + 1
41:      end
42:   
43:      if isZhishu?(i, arrZhishu) && isHuiwen?(i) then
44:          arrZhishu.push(i)
45:          #printf "%4d", i
46:          #print "\n"
47:          count = count + 1
48:      end
49:  end
50:  print "\n\nTotal:#{count}"

转载于:https://www.cnblogs.com/cocowool/archive/2012/05/18/2507843.html

你可能感兴趣的文章
一次完整的HTTP请求是怎样的??
查看>>
【C++】常见的内存泄漏及解决方法
查看>>
【C++】const 指针与指向const的指针
查看>>
【Linux】多线程和多进程 及其应用场景
查看>>
【C++】构造函数中必须通过初始化列表来进行初始化情况
查看>>
【算法】对于大数的操作
查看>>
【操作系统】系统调用的概念
查看>>
【计算机网络】cookie和session的区别
查看>>
【C++】构造函数、析构函数抛出异常的问题
查看>>
【C++】关于vector<bool>
查看>>
【操作系统】内存碎片产生原因及终极解决办法
查看>>
幂等性验证思想
查看>>
DB理论--数据存储方式
查看>>
PB协议的说明与使用
查看>>
什么是TPS,什么是QPS,区别是什么?
查看>>
git pull遇到错误:error: Your local changes to the following files would be overwritten by merge:
查看>>
arraylist扩容时机java8
查看>>
logback中additivity的理解
查看>>
一篇文章搞懂hash,hashcode,equals,==的用法
查看>>
mysql数据库,悲观锁。for update 的用法。
查看>>