I'm trying to use a recursive function Power in Racket that takes as input two
numbers x and y and returns xy, where x and y can be positive or
negative.
;a power b
(printf "Enter value of X: ")
(define a (read))
(printf "Enter value of n: ")
(define b(read))
(define (power a b) (if (= b 0) 1 (* a (power a (- b 1 )))))
(define (DisplayResult a messg b mess res) (display a) (display messg)(display b) (display mess) (display res))
(DisplayResult a " power " b " is " (power a b))
How can the program accept negative power?
We can use this rule:
a^-b = 1 / a^b
or if we insert -b as b:
a^b = 1 / a^-b
Your power handles the case where b is positive, so we can reuse it
to define an extended-power that handles the negative case:
(define (extended-power a b)
(if (negative? b)
(/ 1 (power a (- b)))
(power a b)))
Related
what is the required recursive function(s) in Scheme programming language to compute the following series?? Explanation needed
1^2/2^1 + 3^4/4^3 + 5^6/6^5 + 7^8/8^7 + 9^10/10^9
So, well, what does each term look like? It's n^(n+1)/(n+1)^n. And you want to stop when you reach 10 (so if n > 10, stop). So write a function of a single argument, n, which either:
returns 0 if n > 10;
adds n^(n+1)/(n+1)^n to the result of calling itself on n + 2.
Then this function with argument 1 will compute what you want. Going backwards may be easier:
return 0 if n < 1;
add n^(n+1)/(n+1)^n to the result of calling itself on n - 2;
then the function with argument 10 is what you want.
Or you could do this which is more entertaining:
(define s
(λ (l)
((λ (c i a)
(if (> i l)
a
(c c
(+ i 2)
(+ a (/ (expt i (+ i 1))
(expt (+ i 1) i))))))
(λ (c i a)
(if (> i l)
a
(c c
(+ i 2)
(+ a (/ (expt i (+ i 1))
(expt (+ i 1) i))))))
1 0)))
But I don't recommend it.
//power function
(define (power a b)
(if (zero? b) //base case
1
(* a (power a (- b 1))))) //or return power of a,b
// sum function for series
(define (sum n)
(if (< n 3) //base case
0.5
(+ (/ (power (- n 1) n) (power n (- n 1))) (sum (- n 2 )) ))) //recursion call
>(sum 10) // call sum function here .
I've got this:
(let ((num 1))
(mapcar (lambda (x)
(cons x (if (evenp (setf num (random 299)))
(1+ num)
(num))))
'(a b c d e f)))
which should produce something like this:
((A . 37) (B . 283) (C . 232) (D . 251) (E . 273) (F . 170)
only with odd numbers. Yes, very kludgy looking. Is there something with random-state that would help? Or the "hidden system variable" that holds onto that initial random calculation? Here's a global function I tried:
(defun random-odd ()
(let ((num 0))
(if (evenp (setf num (random 299)))
(1+ num)
(num))))
Also not working. What am I missing here?
Your random-odd is almost fine except for the style and using num in
the function position (remember, Lisp parentheses are meaningful):
(defun random-odd ()
(let ((num (random 299)))
(if (evenp num)
(1+ num)
num)))
The subtle problem with this function is that the probability of getting 299 is half the probability of getting any other odd number from 1 to 297.
This is because (random 299) returns numbers from 0 to 298 inclusive with equal probability 1/299. Thus random-odd will return, say, 17 with probability 2/299 (if random returns 17 or 16) but it will return 299 with probability 1/299 (if random returns 298).
Thus I would suggest
(defun random-odd (even-limit)
"Return an odd random number from 0 to EVEN-LIMIT, exclusive."
(assert (evenp even-limit) (even-limit)
"~S: ~S must be even" 'random-odd 'even-limit)
(let ((num (random even-limit)))
(if (evenp num)
(1+ num)
num)))
A completely equivalent approach would be
(defun random-odd (half-limit)
"Return a random odd number from 1 to half-limit*2-1 inclusive."
(1+ (ash (random half-limit) 1)))
(mapcar #'(lambda (x)
(let ((num (random 299)))
(cons x (if (evenp num)
(1+ num)
num))))
'(a b c d e f))
I'm trying to create a Division function using only subtraction. What I have so far is enough to handle positive numbers. What keeps tricking me up is handling it for negative numbers. I can go ahead and just grab the absolute value of x and y and it works perfectly, but then my answer can never be negative. Anyone here whose had to do something similar before?
(define Divide (lambda (a b c)
(if (> a 0)
(Divide (- a b) b (+ c 1))
c
)
)
)
You can assign the product of sign values of a and b to a variable, then deal with only absolute values of both a and b while doing the recursion. Output then becomes the product of c and the sign variable as (* c sign). Consider the following:
(define (divide num denom)
(let div ([n num]
[d denom]
[acc 0]
[sign 1])
(cond
[(< n 0)
(div (- n) d acc (- sign))]
[(< d 0)
(div n (- d) acc (- sign))]
[(< n d)
(* sign acc)]
[else
(div (- n d) d (add1 acc) sign)])))
For example,
> (divide 10 7)
1
> (divide -10 7)
-1
> (divide -10 -7)
1
> (divide 10 -7)
-1
Note that if you use the condition (if (> a 0) ... instead of (if (>= a b) ..., then you add an extra step in your recursion, which is why using your function, (Divide 10 7 0) outputs 2.
In cases like this you often want to define an auxiliary function that the main function calls after massaging the data:
(define (Divide a b)
(define (go a b c)
(if (> a 0)
(go (- a b) b (+ c 1))
c))
(cond
[(and (> a 0) (> b 0))
(go a b 0)]
[(and (< a 0) (< b 0))
(go (- a) (- b) 0)]
[(< a 0)
(- (go (- a) b 0))]
[(< b 0)
(- (go a (- b) 0))]))
I am trying to convert a binary number entered as "1010" for 10 using recursion. I can't seem to wrap my head around the syntax for getting this to work.
(define (mod N M)
(modulo N M))
(define (binaryToDecimal b)
(let ([s 0])
(helper b s)))
(define (helper b s)
(if (= b 0)
(begin (+ s 0))
(begin (* + (mod b 2) (expt 2 s) helper((/ b 10) + s 1)))))
Thanks!
Here's a simple recursive solution:
(define (bin->dec n)
(if (zero? n)
n
(+ (modulo n 10) (* 2 (bin->dec (quotient n 10))))))
testing:
> (bin->dec 1010)
10
> (bin->dec 101)
5
> (bin->dec 10000)
16
If you want "1010" to translate to 10 (or #b1010, #o12 or #xa) you implement string->number
(define (string->number str radix)
(let loop ((acc 0) (n (string->list str)))
(if (null? n)
acc
(loop (+ (* acc radix)
(let ((a (car n)))
(- (char->integer a)
(cond ((char<=? a #\9) 48) ; [#\0-#\9] => [0-9]
((char<? a #\a) 55) ; [#\A-#\Z] => [10-36]
(else 87))))) ; [#\a-#\z] => [10-36]
(cdr n)))))
(eqv? #xAAF (string->number "aAf" 16)) ; ==> #t
It processes the highest number first and everytime a new digit is processed it multiplies the accumulated value with radix and add the new "ones" until there are not more chars. If you enter "1010" and 2 the accumulated value from beginning to end is 0, 0*2+1, 1*2+0, 2*2+1, 5*2+0 which eventually would make sure the digits numbered from right to left 0..n becomes Sum(vn*radic^n)
Now, if you need a procedure that only does base 2, then make a wrapper:
(define (binstr->number n)
(string->number n 2))
(eqv? (binstr->number "1010") #b1010) ; ==> #t
I'm a newbie in LISP. I'm trying to write a function in CLISP to generate the first n numbers of Fibonacci series.
This is what I've done so far.
(defun fibonacci(n)
(cond
((eq n 1) 0)
((eq n 2) 1)
((+ (fibonacci (- n 1)) (fibonacci (- n 2))))))))
The program prints the nth number of Fibonacci series. I'm trying to modify it so that it would print the series, and not just the nth term.
Is it possible to do so in just a single recursive function, using just the basic functions?
Yes:
(defun fibonacci (n &optional (a 0) (b 1) (acc ()))
(if (zerop n)
(nreverse acc)
(fibonacci (1- n) b (+ a b) (cons a acc))))
(fibonacci 5) ; ==> (0 1 1 2 3)
The logic behind it is that you need to know the two previous numbers to generate the next.
a 0 1 1 2 3 5 ...
b 1 1 2 3 5 8 ...
new-b 1 2 3 5 8 13 ...
Instead of returning just one result I accumulate all the a-s until n is zero.
EDIT Without reverse it's a bit more inefficient:
(defun fibonacci (n &optional (a 0) (b 1))
(if (zerop n)
nil
(cons a (fibonacci (1- n) b (+ a b)))))
(fibonacci 5) ; ==> (0 1 1 2 3)
The program prints the nth number of Fibonacci series.
This program doesn't print anything. If you're seeing output, it's probably because you're calling it from the read-eval-print-loop (REPL), which reads a form, evaluates it, and then prints the result. E.g., you might be doing:
CL-USER> (fibonacci 4)
2
If you wrapped that call in something else, though, you'll see that it's not printing anything:
CL-USER> (progn (fibonacci 4) nil)
NIL
As you've got this written, it will be difficult to modify it to print each fibonacci number just once, since you do a lot of redundant computation. For instance, the call to
(fibonacci (- n 1))
will compute (fibonacci (- n 1)), but so will the direct call to
(fibonacci (- n 2))
That means you probably don't want each call to fibonacci to print the whole sequence. If you do, though, note that (print x) returns the value of x, so you can simply do:
(defun fibonacci(n)
(cond
((eq n 1) 0)
((eq n 2) 1)
((print (+ (fibonacci (- n 1)) (fibonacci (- n 2)))))))
CL-USER> (progn (fibonacci 6) nil)
1
2
1
3
1
2
5
NIL
You'll see some repeated parts there, since there's redundant computation. You can compute the series much more efficiently, however, by starting from the first two numbers, and counting up:
(defun fibonacci (n)
(do ((a 1 b)
(b 1 (print (+ a b)))
(n n (1- n)))
((zerop n) b)))
CL-USER> (fibonacci 6)
2
3
5
8
13
21
An option to keep the basic structure you used is to pass an additional flag to the function that tells if you want printing or not:
(defun fibo (n printseq)
(cond
((= n 1) (if printseq (print 0) 0))
((= n 2) (if printseq (print 1) 1))
(T
(let ((a (fibo (- n 1) printseq))
(b (fibo (- n 2) NIL)))
(if printseq (print (+ a b)) (+ a b))))))
The idea is that when you do the two recursive calls only in the first you pass down the flag about doing the printing and in the second call instead you just pass NIL to avoid printing again.
(defun fib (n a b)
(print (write-to-string n))
(print b)
(if (< n 100000)
(funcall (lambda (n a b) (fib n a b)) (+ n 1) b (+ a b)))
)
(defun fibstart ()
(fib 1 0 1)
)