Posted: Fri Jun 09, 2006 11:57 am Post subject: (No subject)
Don't really know what to do to learn some more C++, having trouble finding anything about Voids (Except programs that already have them, in which case they don't explain what they are, or how they work). I guess I could mess around and figure them out, but I like tutorials (More then one, and then experimenting, so I don't get the wrong idea).
Since I was bored, I made an extremely simple recursive factoring program. Im terrible at recursive programs (I can formulate them in my head, but writing the code I have no were to start.), practice breeds improvement right?
For something this simple, we might also rewrite this as:
code:
double Factor(double x)
{
return x == 1 ? 1 : x * Factor(x - 1);
}
Secondly, there's a problem with using floating point numbers in this case. Let's say we write:
code:
Factor(1.5)
Now, since this isn't 1, we next execute:
code:
1.5 * Factor(0.5)
And 0.5 isn't 1, so next...
code:
1.5 * 0.5 * Factor(-0.5)
Will this ever terminate?
Flikerator
Posted: Fri Jun 09, 2006 12:26 pm Post subject: (No subject)
At first I thought about putting an else, but realised it wasn't needed, because its just extra code for no reason. Unless im missing something.
That is really neat. As I understand it;
does x == 1? then return 1
Then the ":" would be like an else right? Thats really neat.
As for that error, it was meant only to be ints. Why I put Double I have no idea. Ive never heard of Factoring real numbers My Turing version has ints so I guess I goofed =P
Thanks wtd for all the help ^_^
Null
Posted: Sat Jun 10, 2006 10:43 am Post subject: (No subject)
Just a note. This is not rule by any means, but functions in C++ typically begin with a lowercase letter.
wtd
Posted: Sat Jun 10, 2006 11:26 am Post subject: (No subject)
Additionally, what is being done is not "factoring", but generating a factorial. The function name should indicate this.
A recursive factorial function with O(1) space properties:
code:
let factorial n =
let rec aux n acc =
if n = 0 then acc
else aux (n - 1) (n * acc)
in
aux n 1
Or perhaps:
code:
(defgeneric factorial (n))
(defmethod factorial ((n integer))
(labels ((aux (n acc)
(if (equalp n 0)
acc
(aux (- n 1) (* n acc)))))
(aux n 1)))
Andy
Posted: Sat Jun 10, 2006 9:18 pm Post subject: (No subject)
Null wrote:
Just a note. This is not rule by any means, but functions in C++ typically begin with a lowercase letter.
Just a note. This is not a rule by any means, but people generally read a few pages ahead before posting