免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1706 | 回复: 2
打印 上一主题 下一主题

一个智能匹配找质数的问题 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2012-11-12 19:49 |只看该作者 |倒序浏览
本帖最后由 无双六 于 2012-11-12 19:50 编辑

代码如下:
  1. #!usr/bin/perl
  2. use 5.014;
  3. use utf8;
  4. use strict;

  5. sub divisors {
  6.         my$number = shift;
  7.         my@divisors = ();
  8.         foreach my$divisor ( 2 .. ( $number/2 ) ) {
  9.                 push @divisors, $divisor unless $number % $divisor;
  10.         }
  11.         return @divisors;
  12. }

  13. say "Checking the number <$ARGV[0]>";

  14. given ( $ARGV[0] ) {
  15.         when ( ! /\A\d+\Z/ )        {say "It's not a number!"}

  16.         my@empty = ();
  17.         when ( &divisors ~~ @empty )        {say "It is a prime"}
  18.        
  19.         my@divisors = &divisors( $_ );
  20.         default        {say "It's factor is @divisors"}
  21. }
复制代码
要求是输入一个数,是质数就输出"It is a prime",不是就输出它的因数。

运行结果其余都没问题,就是输入质数的时候,输出是"It's factory is    ",看起来是"divisors ~~ @empty"没有匹配成功,试了几种判定方法都不行。

论坛徽章:
0
2 [报告]
发表于 2012-11-13 08:41 |只看该作者
  1. #!/opt/perl5.14/bin/perl
  2. use strict;
  3. use 5.014;

  4. say "check is '$ARGV[0]'";
  5. given($ARGV[0]){
  6.         when(! /\A\d+/) {say "not is number"}
  7.         my @return=&drivesrs($_);
  8.         my @temp;
  9.         when(@return ~~ @temp){say "number is prime"}
  10.         default {say "$_ is divisible by @return"}
  11. }
  12. sub drivesrs {
  13.         my $number=shift;
  14.         my @div;
  15.         foreach(2..($number/2)){
  16.                 push @div,$_ unless $number%$_;
  17.         }
  18.         return @div;
  19. }
复制代码

论坛徽章:
0
3 [报告]
发表于 2012-11-13 20:57 |只看该作者
回复 2# wsxedcer


    原来如此,多谢
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP