as the title says im trying to code recursive for x^n without the expt function. If n is even it should: (x^n/2)^2 otherwise when its uneven x*x(^n-1) and obviously n=0 should be 1.
(define fast-power (lambda (x n) (cond [(and (number? x) (naturalnumber0? n)) (fast-power-internal x n)] [else (error 'fast-power "invalid input.")])))
(define (fast-power-internal x n) (cond n 0) 1] [ (even? n) ??? else ???
(define (naturalnumber0? n) (if (and (isinterger? n) (<= 0 n)) true false))
(define (isinterger? x ) x (floor x)) 0))
on the ??? lines im not sure how to make it recursive with 2 variables. Can anyone give me a hint?
There are several errors with your attempt. Starting with a simple function definition -
Let's add some line breaks and inline comments -
Note racket has many built-ins for identifying number types.
integer?natural?zero?positive?even?etc. You can implement them yourself if you are careful to avoid mistakes but we will use Racket's in the section below.The problem defines the result in expressions using
^. I would suggest to first rewrite these without^When
nis zero -(inductive:
nis non-zero) Whennis even -Translated to scheme -
We can avoid duplicate computation using
letassignment -(inductive:
nis non-zero,nis non-even) Otherwisenis odd -Translated to scheme -
As for your recursive function, I don't think you need an auxiliary helper. I find it useful to identify error cases before attempting the recursive logic. The
condexpression is only concerned with the "happy path" of the program -Note:
quotientreturns the integer result of division./returns a number.Note: Use the
Racket > Reindentoption to format the source code for you automatically.contracts
Using
invariantlike I did above is an effective means for handling bad inputs to your programs, however writing code like this can feel like a chore. Racket makes all of this easier with contracts. Let's seefast-powerwritten using a contract -The contract is explained as -
Re-run the program to see the contract enforced -
Our contract enforces
nmust be a natural numberNote: define/contract is a macro provided by the
racket/contract.