Qbasicnews.com

Full Version: Challenge: Algorithms having only one line of code.
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2 3 4 5 6 7 8 9 10
Oh, you want to compute the factorial of a number. Well, for the moment, I can't see how you can do that in one line of code, without a function of course. Normally a factorial is computed using a FOR loop. That doesn't mean that it can't be done. Keep trying.
*****
Here's a little algorithm that I derived.

Given a positive integer number N, compute the next multiple of X:
Result to M.

defint a-z

M = int((N+X)/X)*X

Note: "next" multiple means that if you're already at a multiple, you move up to the next multiple. Example: if N=5 and X=5, the result will be 10.

If you got that, then make a slight change to the algorithm to compute the "nearest" multiple. Example: if n=5 and x=5, the result is 5 because it is the nearest (you're already there). This is like rounding --- if it's already rounded, then that's the answer.
*****
Factorial in one line?
Code:
function fact&(x&):if x& then fact&=x&*fact&(x&-1) else fact&=1 :end function
Wow, Antoni! A recursive call to itself --- very sofisticated!
Let me try it out .
*****
Scolta noi ------------- it works!
Brilliant, Antoni.

*****
I have not tested it, but I think it does'nt work.
END FUNCTION can't be in the same line of a single line IF...
Antoni, What I tested was the your one line of code in between a standard Function definition line and a standard End Function line.
It's still a one line function.
*****
Thanks for considering it like this!
HEY! NO FAIR!

IT's THREE LINES OF CODE!
I don't understand what that function does or what a factoral is. Please explain EVERYTHING IN THE UNIVERSE to me.

Nevermind. Some jerk named dictionary.com very rudely explained it to me...
Well, in the line of Antoni's, here's my very own fibonnaci series callculator:

Code:
FUNCTION fibonacci& (n&)
   IF n& < 2 THEN fibonacci& = 1 ELSE fibonacci& = fibonacci&(n& - 1) + fibonacci&(n& - 2)
END FUNCTION

You use it this way (for example):

Code:
FOR i& = 0 TO 10
   PRINT fibonacci(i&)
NEXT
Pages: 1 2 3 4 5 6 7 8 9 10