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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?