A solution to the idea of a logical arithmetic algorithm

Source: Internet
Author: User
The idea of asking a logical arithmetic algorithm


The meaning is that a is the parent of B, B is the parent of C, and so on, infinitely deferred classification;
Each of these members has a corresponding value, which is a random number with a value of 1-30;
Now it's time to calculate that when I randomly select a member, I can calculate the sum of the value values accumulated by this member and all of the parent members up to which member the total value exceeds 200.


------Solution--------------------
Recursion.

Recursive functions within a class
function test ($id, $num =0, $max =200) {
$sql = "Select * from {{test}}" WHERE id= $id ";
$res =yii::app ()->db->createcommand ($sql)->queryrow ();
$num + = $res [' value '];
if ($num < $max) {
$name =self::test ($res [' pid '], $num);
}else{
$name = $res [' name '];
}
return $name;
}

Call
$tr =new classtest ();
Echo $tr->test (7);
Result D

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.