0

I need to return a result of (1 / n!) * (1! + 2! + 3! + ... + n!), n>=1. This is a CodeWars challenge! The code below returns 1.146652 for n = 8, but the correct result is 1.1466510000000001 or 1.146651.

How can I truncate this number correctly?

function factorial($val){
  $factor = 1;
  for($i=1;$i<=$val;$i++){
    $factor *= $i;
  }
  return $factor;
}

function going($n) {
  $val = 1/factorial($n);
  $somatorio = 0;
  for($i=1;$i<=$n;$i++){
    $somatorio += factorial($i);
  }

  return round($val * $somatorio,6);
}
João Victor
  • 639
  • 6
  • 20
  • 3
    Your math may be wrong somewhere, because `$val * $somatorio` equals 1.1466517857143 on my system, which rounds up. – aynber Nov 17 '16 at 17:26
  • Can i simply cut the number at 6 decimal place? – João Victor Nov 17 '16 at 17:27
  • 1
    Yes, try number_format: http://php.net/number_format – aynber Nov 17 '16 at 17:33
  • see https://stackoverflow.com/questions/5093608/how-can-i-make-sure-a-float-will-always-be-rounded-up-with-php, replace `ceil` and `up` with `floor` and `down`. – Lutz Lehmann Nov 17 '16 at 17:33
  • 2
    round resulting in 1.146652 is correct, since the digit number 7 is higher than 5, thus it rounds the 1 up to a 2. if you absolutely want the code to ignore the digits coming after the 6th digit, then you can use `floor`. –  Nov 17 '16 at 17:38
  • The correct result is 1,146651786! because the 1.146652 is correct! – adampweb Nov 17 '16 at 17:39

0 Answers0