Skip to content

Instantly share code, notes, and snippets.

@games647
Created November 23, 2016 14:09
Show Gist options
  • Save games647/c680a7e5d687b310030267e685a2181a to your computer and use it in GitHub Desktop.
Save games647/c680a7e5d687b310030267e685a2181a to your computer and use it in GitHub Desktop.
Converts a number from base-10 to base-x
;; The first three lines of this file were inserted by DrRacket. They record metadata
;; about the language level of this file in a form that our tools can easily process.
#reader(lib "htdp-intermediate-lambda-reader.ss" "lang")((modname newton-method) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f)))
;; length-representation: number number -> number
;;
;; Outputs the lowester exponent for b which is higher than x
;;
;; Example: (length-representation 10 2) = 4
(define (length-representation x b)
(local
[(define (length-representation i) (if (> (expt b i) x)
i
(length-representation (add1 i))))]
(length-representation 0)))
;; Tests
(check-expect (length-representation 2 2) 2)
(check-expect (length-representation 8 4) 2)
(check-expect (length-representation 10 2) 4)
;; convert: number number -> (listof number)
;;
;; Converts a number from the base-10 number system to number with the given base
;;
;; Example: (convert 10 2) = '(1 0 1 0)
(define (convert x base)
(cond [(<= x 0) empty]
[(= 0 (remainder x base)) (cons 1 (convert (/ x base) base))]
[else (cons 0
(convert (floor (/ x base)) base))]))
;; Tests
(check-expect (convert 0 5) empty)
(check-expect (convert 10 2) '(1 0 1 0))
(check-expect (convert 16 16) '(1 0))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment