🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

3 total messages Started by Jacob Gore Mon, 06 Apr 1992 02:51
can this be implemented in O(1) space?
#3
Author: Jacob Gore
Date: Mon, 06 Apr 1992 02:51
15 lines
815 bytes
Consider the following function for computing x to the power of n:

fun power(x,n) =
  if n=0 then 1.0
  else if n mod 2 = 1 then x * power(x,n-1)
  else power(x*x, n div 2);

What is the likelihood of an SML implementation doing it in O(1) space?

Jacob
--
Jacob Gore			Mathematical and Computer Sciences
<JGore@Mines.Colorado.Edu>	Colorado School of Mines

	-- Member of the League for Programming Freedom --
Re: can this be implemented in O(1) space?
#4
Author: Marc Najork
Date: Mon, 06 Apr 1992 18:14
31 lines
1420 bytes
In article <1992Apr06.025126.33552@slate.mines.colorado.edu>, jgore@Mines.Colorado.Edu (Jacob Gore) writes:
> Consider the following function for computing x to the power of n:
> 
> fun power(x,n) =
>   if n=0 then 1.0
>   else if n mod 2 = 1 then x * power(x,n-1)
>   else power(x*x, n div 2);
> 
> What is the likelihood of an SML implementation doing it in O(1) space?
> 
> Jacob
> --
> Jacob Gore			Mathematical and Computer Sciences
> <JGore@Mines.Colorado.Edu>	Colorado School of Mines
> 
> 	-- Member of the League for Programming Freedom --

If you transform this into a tail-recursive form, i.e.

        fun power(x,n) =
          auxpower(x,n,1.0);

        fun auxpower(x,n,res) =
          if n=0 then res
          else if n mod 2 = 1 then power(x,n-1,res*x)
          else power(x*x, n div 2,res);

then a good compiler should recognize that it is a tail-recursion, and
convert it into an iterative form, which would need constant space.

-- Marc Najork
Re: can this be implemented in O(1) space?
#6
Author: Scott Draves
Date: Mon, 06 Apr 1992 19:37
24 lines
1396 bytes
>>>>> On 6 Apr 92 02:51:26 GMT, jgore@Mines.Colorado.Edu (Jacob Gore) said:

Jacob> fun power(x,n) =
Jacob>   if n=0 then 1.0
Jacob>   else if n mod 2 = 1 then x * power(x,n-1)
Jacob>   else power(x*x, n div 2);

Jacob> What is the likelihood of an SML implementation doing it in O(1) space?

well, i don't know the internals of any SML implementations, but one
would assume that the answer is 0% due to the non-tail recursive call
in the second case.  you can easily rewrite the function so that most
compilers will take O(1) space: 

 fun power(x,n,r) : int =
   if n=0 then r
   else if n mod 2 = 1 then power(x,n-1,x*r)
   else power(x*x, n div 2,r);

call it with r=1
-- 
			conform
scott draves		deform
spot@cs.cmu.edu		explode
Thread Navigation

This is a paginated view of messages in the thread with full content displayed inline.

Messages are displayed in chronological order, with the original post highlighted in green.

Use pagination controls to navigate through all messages in large threads.

Back to All Threads