0

I am writing a program to sum the digits of a number , it is working fine for small numbers but for large no it is giving unexpected sum? below is the program.

<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
class demo {
    private $sum = 0;
    private $num = 0;
    private $rem = 0;

    public function digit_sum($digit) {
        //echo gettype($digit).'<br>';
        try {
            if (gettype($digit) == 'string') {
                throw new Exception($digit . ' is not a valid number <br>');
            } else {
                $this->num = $digit;
                while ($this->num > 0) {
                    $this->rem = $this->num % 10;
                    $this->sum = $this->sum + $this->rem;
                    $this->num = $this->num / 10;
                }
                return "Sum of no  $digit is = " . $this->sum . '<br>';
            }
        } catch (Exception $e) {
            echo $e->getMessage();
        }
    }

}

$sum = new demo();
echo $sum->digit_sum('sfsdfsdfds');
echo $sum->digit_sum(12345);
// outputs correct sum
echo $sum->digit_sum(3253435674);
//outputs incorrect sum

i see the above code results fine for integer no but not for double no' please guide me what will be the perfect solution to this problem?

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
Atul Kumar
  • 83
  • 1
  • 6

1 Answers1

0

Do you know if you put a new echo $sum->digit_sum(32); The output will show you 62. Cause you create object once and call the same function multiple times. The object stores the sum for all the times.

Solution:

Just put an statement $this->sum = 0; before the while loop to clear the previous sum.

Online Example: https://3v4l.org/C7Yli.

Update: I tested the scripts in writephponline.com as per your comment and get the following result.

enter image description here

Murad Hasan
  • 9,565
  • 2
  • 21
  • 42
  • yes you are right , but i have php 7 , $sum->digit_sum(3253435674) giving me 36 instead of 42. i am checking this code on http://www.writephponline.com/ and result is 42 for same code. – Atul Kumar Oct 02 '16 at 13:29
  • And what is in the output of the online example?? __Output for 5.6.0 - 5.6.26, hhvm-3.10.0 - 3.14.4, 7.0.0 - 7.1.0RC3__, In these versions the output will be same. – Murad Hasan Oct 02 '16 at 15:41