Question

I have written a little script to automate some calculations for me. It is pretty simple. 1*3=3 2*3=6 3*3=9 and so on. When the answer(product) is more than one digit long I want it to add the digits of the answer. 3*4=12 || 1+2=3. I want it to automatically add the answer if it is more than one digit no matter how many times adding the answer arrives larger than a single digit. as in when you reach 13*3=39 || 3+9=12 || 1+2=3 Currently my code does not loop, and i cannot figure out how to make it loop here.

http://screencast.com/t/MdpQ9XEz

Also, it is not adding up more than 2 digit answers see 34*3=102. any help here to allow it infinity addition would be great. As each line is produced the answers get larger, so it should add as many digits there are in the answer.

here is my code:

$i = 1; //Start with one
function count_digit($number) {
    return strlen((string) $number);
};
 while($i < 500){
    $product = $i * 3; //Multiply set
    $number_of_digits = count_digit($product); //calls function to count digits of $sum

        if($number_of_digits > 1){  //if $sum has more than one digit add the digits together
        $addproduct = strval($product);//seperates the digits of $sum
        $ii = 0;

        while($ii <= $number_of_digits -1){
            $io = $ii + 1;
            if($io < $number_of_digits){
                $one = intval($addproduct[$ii]);
                $two = intval($addproduct[$io]);
                $sum = $one + $two;
                print($i . ' * 3 = ' .$product. ' || ' .$one. ' + ' .$two. ' = ' .$sum. '<br>');
            };$ii++;
        };

    }else{
        Print ($i . ' * 3 = ' .$product.'<br>'); //Print Set
    };
$i++; //add one

}

No correct solution

OTHER TIPS

For a start, you might replace the $i=1, while ..., and $i++ into one statement: for ($i=0; $i<500; $i++) {.... - see http://nz1.php.net/manual/en/control-structures.for.php for more information about for loops. It comes out to effectively the same code, but keeps the three parts (initialisation, test, increment counter) together; it makes it clear that they are related, and quicker to understand.

Next I would replace conversion of the number to a string, seeing if the length of the string is greater than one, etc.... with:

while ($product>10) {
   $out=0;
   while ($product) {
       $out+=$product%10;
       $product=(integer)($product/10);
   }
   $product=$out;
}

Note that at no time am I treating a number as a string - I avoid that wherever possible.

In case you are not familiar with it, $something+=$somethingelse is the same as $something=$sometime+$somethingelse, just a shorthand. $out is the running total, and each time around the inner loop (while $product), $out is increased by the rightmost digit (the ones column): $out+=$product%10 - see http://nz2.php.net/operators.arithmetic for more info, then $product is divided by 10 and converted to an integer, so 12 becomes 1.2, then 1, dropping the right-most digit.

Each time the inner loop is complete (all the digits of $product are used up, and $product is 0), the result (in $out) is copied to $product, and then you get back to the outer loop (to see if the sum of all these digits is now less than 10).

Also important is exactly where in each loop you print what. The first part, with the multiplication, is immediately in the '500' loop; the '||' happens once for each time '$product' is reduced to '$out'; the adding of the digits happens inside the innermost loop, with '+' either BEFORE each digit except the first, or AFTER each digit except the last. Since 'all except the last' is easier to calculate ($product>=10, watch those edge cases!), I chose that one.

Also note that, since I'm adding the digits from the right to the left, rather than left-to-right, the addition is reversed. I do not know if that will be an issue. Always consider if reversing the order will save you a lot of work. Obviously, if they NEED to be done in a particular order, then that might be a problem.

The result is:

 for ($i=0; $i<500; $i++) {
     $product = $i * 3; //Multiply set
     print ($i . ' * 3 = ' .$product);
     while ($product>10) {
         print ' || ';
         $out=0;
         while ($product>0) {
             print ($product%10);
             if ($product>=10) {
                 print " + ";
             }
             $out+=$product%10;
             $product=(integer)($product/10);
         }
         $product=$out;
         print(' = ' .$product);
      }
      print "<br>";
  };

I've decided to add this as a separate answer, because it uses a different approach to answer your question: the least amount of changes to fix the problem, rather than rewriting the code in an easy-to-read way.

There are two problems with your code, which require two separate fixes.

Problem 1: Your code does not add 3 digit (or more) numbers correctly.

If you look carefully at your code, you will notice that you are adding pairs of numbers ($one and $two); each time you add a pair of numbers, you print it out. This means that for the number 102, you are adding 1 and 0, printing out the results, then adding 0 and 2 and printing it out. Look carefully at your results, and you will see that 102 appears twice!

One way to fix this is to use $three and $four (4 digits is enough for 500*3). This is not good programming, because if you later need 5 digits, you will need to and $five, and so forth.

The way to program this is to start with a $sum of zero, then go through each digit, and add it to the sum, thusly:

    $ii = 0;
    $sum = 0;

    while($ii <= $number_of_digits - 1){
        $one = intval($addproduct[$ii]);
        $sum = $sum + $one;
        $ii++;
    }
    print($i . ' * 3 = ' .$product. ' || ' . $sum . '<br>');
    };

The inner if disappears, of course, since it relates to $io, which we are no longer using.

Of course, now you lose your ability to print the individual digits as you are adding them up. If you want those in, and since we don't know in advance how many there are, you would have to keep a record of them. A string would be suitable for that. Here is how I would do it:

    $ii = 0;
    $sum = 0;
    $maths = "";

    while($ii <= $number_of_digits-1){
        $one = intval($addproduct[$ii]);

        if ($maths=="") {
            $maths=$one;
        } else {
            $maths=$maths . " + " .$one;
        }

        $sum = $sum + $one;
        $ii++;
    }
    print($i . ' * 3 = ' .$product. ' || ' . $maths . " = " . $sum . '<br>');
    };

Note the lines with $math in them; there's one at the top, setting it to an empty string. Then, once we've decided on what number we're adding, we add this to $maths. The first time round is a special case, since we don't want "+" before our first digit, so we make an exception - if $maths is empty, we set it to $one; later times around the loop, it's not empty, so we add " + " . $one;

Problem 2: if the result of the addition is more than 1 digit long, go around again. And again, as many times as required.

At this point I would suggest a little refactoring: I would break the print statement into several parts. First the multiplication - that can easily be moved to the top, immediately after the actual multiplication. Printing the <br> can go at the end, immediately before the $i++. This also means you no longer need the else clause - it's already done. This only leaves the ' || ' . $maths . " = " . $sum. This is going to have to happen every time you go through the adding.

Now, replace your if($number_of_digits... with a while($number_of_digits...; this means it goes through as many times as is needed, if it's zero or 100. This does mean that you're going to have to update $product at the end of your loop, with $product = $sum; - put this immediately after the print statement. You will also need to update $number_of_digits; copy the line from the top to the end of the loop.

If you've been following along, you should have:

$i = 1; //Start with one
function count_digit($number) {
    return strlen((string) $number);
};
 while($i < 500){
    $product = $i * 3; //Multiply set
    print($i . ' * 3 = ' .$product); // Print basic multiplication
    $number_of_digits = count_digit($product); //calls function to count digits of $sum

        while ($number_of_digits > 1){  //if $sum has more than one digit add the digits together
        $addproduct = strval($product);//seperates the digits of $sum
    $ii = 0;
    $sum = 0;
    $maths = "";

    while($ii <= $number_of_digits-1){
        $one = intval($addproduct[$ii]);

        if ($maths=="") {
            $maths=$one;
        } else {
            $maths=$maths . " + " .$one;
        }

        $sum = $sum + $one;
        $ii++;
    }
    print(" || " . $maths . " = " . $sum ); // print one lot of adding
    $product=$sum;
    $number_of_digits = count_digit($product); //calls function to count digits of $sum
    };
    Print ("<br>"); //go to next line
$i++; //add one
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top