## Arbitrary precision integer math in BASIC

Discuss software for the Apple 1/replica 1

### Arbitrary precision integer math in BASIC

I've been playing around with the doing arbitrary precision math in basic. I figured out one way ( don't know if it's good or not ), that uses arrays. One limitation maybe entering in the numbers. Another, of course is memory.

I wrote a fibonacci calculator that finds fibonacci numbers out to 35 places ( up to the 173'rd number ). It runs pretty fast on dinaao on my MacBook, not so fast on a real Replica 1.

Still, I find that doing math to any precision under a limited environment an interesting problem.

Here is my program ( I'll put it on my Replica 1 page as well ):

Code: Select all
`5 REM 1ST 173 FIBONACCI NUMBERS10 M=17220 N=3630 DIM A(N)40 DIM B(N) 50 DIM C(N)60 K=0: X=170 FOR I=1 TO N80 A(I)=0:B(I)=0:C(I)=090 NEXT I100 B(N)=1110 PRINT "0";: TAB 5120 FOR I=1 TO N130 PRINT A(I);140 NEXT I150 PRINT 160 PRINT "1";: TAB 5170 FOR I=1 TO N180 PRINT B(I);190 NEXT I200 PRINT 210 FOR I=1 TO M220 X=X+1230 PRINT X;: TAB 5240 FOR J=N TO 1 STEP -1250 Z=A(J)+B(J)+K260 K=0:Y=Z/10270 IF Y>0 THEN 500290 C(J)=Z300 NEXT J310 FOR L=1 TO N320 A(L)=B(L)330 NEXT L340 FOR L=1 TO N350 B(L)=C(L)360 NEXT L370 FOR L=1 TO N380 PRINT C(L);390 NEXT L400 PRINT 410 NEXT I420 PRINT 430 END 500 K=Y510 Z=Z-(10*Y)520 GOTO 290`

So, I have three arrays, all the same size, I take two and add them together in the third ( notice the adding loop goes backwards to keep the endian-ness matching the way we write numbers ). I have a carry variable, and logic to handle when there is a carry.

Like I said, I'm not sure how good it is ... but I think it is kinda clever. Just me trying to think like a computer.

- Derrik
Derrik Walker v2.0, RHCE
http://www.doomd.net
lorddoomicus

Posts: 32
Joined: Sep Thu 07, 2006 9:30 pm
Location: Mentor Ohio

You would find this thread interesting then.

http://www.brielcomputers.com/phpBB2/vi ... .php?t=327

One thing I'd suggest is to use base 100 in your arrays and convert to print. You could even use base 256 if you're prepared to work a bit harder on the conversion.

Ken
Kallikak

Posts: 172
Joined: Jan Sun 29, 2006 6:42 pm
Location: Sydney

Of course what I'd really recommend is writing it in assembly. Would be quite straightforward since it only involves adding and carry. Just use the same approach, but the speed will be greatly enhanced.
Kallikak

Posts: 172
Joined: Jan Sun 29, 2006 6:42 pm
Location: Sydney 