您的位置:首页 > 移动开发 > 微信开发

计算质数和回文数的小程序

2012-05-18 15:24 218 查看
Ruby 代码如下
 
def isZhishu?(num)


[code]count = 2


while count < num do


return false if ( num % count ) == 0


count = count + 1


end


 


return true


end


 


def isHuiwen?(num)


s = num.to_s.reverse.to_i


return true if num == s


 


return false


end


 


count = 0


10000.times{ |i|


i = i + 1


if isZhishu?(i) && isHuiwen?(i) then


printf "%4d", i


print "\n"


count = count + 1


end


}


print "\n\nTotal:#{count}"

[/code]

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

 

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

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

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

具体代码如下:

def isZhishu?(num, arrZhishu)


[code]return true if num == 1 || num == 2


count = 2


 


if( arrZhishu.empty? )then


#count = 2


    while count < num do


return false if ( num % count ) == 0


if( count >= 11 ) then


count = count + 2 # Only judge even numbers


else


count = count + 1


end


end


 


    return true


else


arrZhishu.each{|value|


next if value == 1


    return false if ( num % value ) == 0


}


    return true


end


end


 


def isHuiwen?(num)


s = num.to_s.reverse.to_i


return true if num == s


 


return false


end


 


count = 0


arrZhishu = Array.new


i = 0


while i < 10000000 do


if i >= 11 then


i = i + 2


else


    i = i + 1


end


 


if isZhishu?(i, arrZhishu) && isHuiwen?(i) then


arrZhishu.push(i)


#printf "%4d", i


#print "\n"


count = count + 1


end


end


print "\n\nTotal:#{count}"

[/code]

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: