Path: utzoo!attcan!uunet!lll-winken!lll-tis!helios.ee.lbl.gov!pasteur!ucbvax!dewey.soe.berkeley.edu!oster From: oster@dewey.soe.berkeley.edu (David Phillip Oster) Newsgroups: comp.sys.mac.programmer Subject: Re: base 10 --> base 3 ... Message-ID: <25768@ucbvax.BERKELEY.EDU> Date: 23 Aug 88 22:44:40 GMT References: <730059@hpcilzb.HP.COM> Sender: usenet@ucbvax.BERKELEY.EDU Reply-To: oster@dewey.soe.berkeley.edu.UUCP (David Phillip Oster) Organization: School of Education, UC-Berkeley Lines: 37 In article <730059@hpcilzb.HP.COM> tedj@hpcilzb.HP.COM (Ted Johnson) writes: >Does anyone know of an algorithm to convert a positive integer N into >its base 3 representation? You are going to feel pretty silly when I tell you the answer to this: --------------------------------- ConvertBase(n, base){ if(n >= base) ConvertBase(n/base, base) Output(n%base); } --------------------------------- where OutPut(digit) will emit the digit as the final result. Note: all the declarations here default to short int, so I don't have to explicitly declare anything. To convert this routine to pascal, declare everything and replace '%' by ' mod ' so, for example, calling ConvertBase(100, 10) will call: Output(1) Output(0) Output(0) A sample definition of Output() is: Output(digit){ putchar('0' + digit); } Note: this routine uses stack space proportional to the log to the base "base" of its argument "n". Don't call it with a base of 0 or 1! For a base of 2 or greater, it will never use more than 16 stackframes for 16 bit integers, which is perfectly reasonable. --- David Phillip Oster --When you asked me to live in sin with you Arpa: oster@dewey.soe.berkeley.edu --I didn't know you meant sloth. Uucp: {uwvax,decvax,ihnp4}!ucbvax!oster%dewey.soe.berkeley.edu