Advertisement
kachamaka

Racket #2

Oct 14th, 2021 (edited)
1,912
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Racket 2.04 KB | None | 0 0
  1. #lang racket
  2.  
  3. ;(remainder 10 3) -> 1
  4.  
  5. (define (gcd a b)
  6.   (cond
  7.     [(= a b) a]
  8.     [(> a b) (gcd (- a b) b)]
  9.     [else (gcd a (- b a))]))
  10.  
  11.  
  12. (define (mymaxdivisor x)
  13.   (define (iteratedivisors d)
  14.           (if (= (remainder x d) 0)
  15.               d
  16.               (iteratedivisors (- d 1))))
  17.   (if (= x 1)
  18.       x
  19.       (iteratedivisors (- x 1))))
  20.  
  21. ;(mymaxdivisor 53)
  22.  
  23. (define (sum-odds a b)
  24.   (define (iterator i sum)
  25.     (if (and (>= i a) (<= i b))
  26.         (if (not (= (remainder i 2) 0))
  27.             (iterator (+ i 1) (+ sum i))
  28.             (iterator (+ i 1) sum))
  29.         sum))
  30.   (iterator a 0))
  31.  
  32. ;(sum-odds 0 10)
  33.  
  34. (define (prime? n)
  35.   (define upper (floor (sqrt n)))
  36.   (define (iterator i)
  37.     (if (> i upper)
  38.         #t
  39.         (if (= (remainder n i) 0)
  40.             #f
  41.             (iterator (+ i 1)))))
  42.   (iterator 2))
  43.  
  44. ;(prime? 19)
  45.  
  46.  
  47. (define (reverse n)
  48.   (define (numlen num len)
  49.     (if (= num 0)
  50.         len
  51.         (numlen (quotient num 10) (+ len 1))))
  52.  
  53.   (define len (numlen n 0))
  54.   (define (iterator i num rev)
  55.     (if (>= i 0)
  56.         (iterator (- i 1) (quotient num 10)  (+ rev (* (remainder num 10) (expt 10 i))))
  57.         (/ rev 10)))
  58.   (iterator len n 0))
  59.  
  60. ;better reverse function
  61. ;(define (numlen num len)
  62. ;    (if (= num 0)
  63. ;        len
  64. ;        (numlen (quotient num 10) (+ len 1))))
  65. ;(define (revs n)
  66. ;  (if (< n 10)
  67. ;      n
  68. ;      (+ (* (remainder n 10) (expt 10 (- (numlen n 0) 1)))
  69. ;         (revs (quotient n 10)))))
  70.  
  71.  
  72. (define (count-palindromes a b)
  73.  (define (palindrome? n)
  74.    (if (= n (reverse n))
  75.        #t
  76.        #f))
  77.  
  78.   (define (iterator i count)
  79.    (if (and (>= i a) (<= i b))
  80.         (if (palindrome? i)
  81.             (iterator (+ i 1) (+ count 1))
  82.             (iterator (+ i 1) count))
  83.         count))
  84.   (iterator a 0))
  85.  
  86.  
  87.  
  88. (define (count-divisors n)
  89.   (define (iterator i count)
  90.     (if (< i 1)
  91.         count
  92.         (if (= (remainder n i) 0)
  93.             (iterator (- i 1) (+ count 1))
  94.             (iterator (- i 1) count))))
  95.   (iterator n 0))
  96.            
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement