douyousu9691 2014-08-10 00:08
浏览 26
已采纳

在字符串中查找素数和复合数

I have the following randomly generated string:

$text = 's$bp4q1hsq3@g88nsjm5hr#i9#3078e2m';

What I need is to take all integers from it and classify them as either prime or composite numbers and estimate their sum. All numbers should be assumed that are one digit so this shortens the values to only four per each group:

$primes     = array(2, 3, 5, 7);
$composites = array(4, 6, 8, 9);

This means: Primes: 5, 3, 3, 2 = 13 and Composites: 4, 8, 8, 9, 8 = 37 as duplicate numbers also count.

I have tried grabbing the numbers like so:

$asArray = str_split($text);

foreach ($asArray as $element) {
    if (is_int($element)) {
        echo $element;
    }
}

But it seems to end up in a blank page. So my question is how can I find out the numbers in a string and then classify them as either prime or composite?

  • 写回答

1条回答 默认 最新

  • douxie1957 2014-08-10 00:30
    关注

    Here you have the sum of the primes and composites:

    $text = 's$bp4q1hsq3@g88nsjm5hr#i9#3078e2m';
    $primes     = array(2, 3, 5, 7);
    
    $sum_primes = $sum_composites = 0; 
    
    preg_match_all("/\d/", $text, $matches);
    
    foreach($matches[0] as $number)
    {
        if (in_array($number, $primes))
            $sum_primes += $number; 
        else
            $sum_composites += $number; 
    } 
    
    echo "Sum of primes: ".$sum_primes."
    ";
    echo "Sum of composites: ".$sum_composites."
    ";
    

    It would print,

    Sum of primes: 20
    Sum of composites: 38
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 求数学坐标画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站