470,864 Members | 1,997 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 470,864 developers. It's quick & easy.

really big integer

I need to calculate the sum of the following numbers

1+ 11 + 111 + 1111 + ......+ 1111.....11111 (the last one is a number
made by 2002 1's )

so, I wrote
$res =0;
for ($i = 1; $i<2003; $i++){
echo str_repeat("1", $i).'<br>';
$res += str_repeat("1", $i);
}

echo 'El resultado total es:<br>';
echo $res;

All works pretty well, and after a really small piece of time, I get:

1.2345679012346E+308

but the result seems to be wrong, beacause I do know (given that I have
a math proof), that it should have 224 1's inside, and as fas as I
know,

1.2345679012346E+308 means 1.2345679012346 * 10^308

which obviously doesn't have such amount of 1's (in fact only has 2 )

Can anyone point me where is the mistake?

sdos - jm

Mar 17 '06 #1
1 1253
julian_m said the following on 17/03/2006 20:02:
I need to calculate the sum of the following numbers

1+ 11 + 111 + 1111 + ......+ 1111.....11111 (the last one is a number
made by 2002 1's )

so, I wrote
<...SNIP...> All works pretty well, and after a really small piece of time, I get:

1.2345679012346E+308

but the result seems to be wrong
Can anyone point me where is the mistake?

You can't fully represent a number with 2000-ish significant digits with
normal integers or floats, nor can you represent a number bigger than
~10^308 with floats. So that's two reasons why this doesn't work!

You'll need to use an arbitrary-length integer library, e.g. BCMath.
--
Oli
Mar 17 '06 #2

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

9 posts views Thread by Christopher Weaver | last post: by
12 posts views Thread by Alex Pierson | last post: by
131 posts views Thread by pemo | last post: by
3 posts views Thread by michael | last post: by
12 posts views Thread by RICHARD BROMBERG | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.