1

I want to take integer input in PHP but the integer can be up to 10^12

<?php

$input = fopen('php://stdin', "r");
fscanf($input, "%d", $x);
print $x;
?>

The above code do not works for input after 10^10.How can we take this integer input?Here is the link

3
  • You can use a float instead - floats are precise for integers up to 2^51, which is far, far more than the 10^12 you need. You can then do validation to ensure it's an integer value, etc. Commented Jun 4, 2014 at 10:58
  • why can't we use integer as an input just like in C++ Commented Jun 4, 2014 at 10:59
  • Because 10^12 > 2^31. But if you have the 64-bit version of PHP then you're all set because 10^12 ≪ 2^63 Commented Jun 4, 2014 at 11:34

1 Answer 1

3

Well yes, you cannot have an int beyond a certain limit (depending on 32 or 64 bit platform). Your alternative is to use a float instead, but this is unsuitable if you require absolute precision. The other alternative is to keep the number as string, and operate on it as string using the bc math functions.

$number = file_get_contents('php://stdin');
if (!ctype_digit($number)) {
    trigger_error("$number is not a number");
}
echo $number;
echo bcadd($number, 42);
Sign up to request clarification or add additional context in comments.

3 Comments

+1 for bc math, but floats do have absolute precision for integers up to the size of the mantissa ;)
@Niet So, they are precise, unless they aren't...? ;)
Hehe, fair point. They're precise under certain circumstances, which is generally good enough for me - although I've learned to always use things like += 0.125 rather than += 0.1 when expecting exact results.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.