Summary Files Commits Branches @commit @diff @stats
path: root / Year 2 / Functional Programming / 03-Practice-20.10.2022.rkt
blob: 7e00afb0698c1142f9b6e0a7450c7942faec33de (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#lang racket

;;; Задача 1

(define (smallest-prime n)
  (cond [(= (remainder n 2) 0) 2]
        [(= (remainder n 3) 0) 3]
        [else (define (find-prime-iter n i maxd)
                (cond [(> (sub1 i) maxd) n]
                      [(= (remainder n (sub1 i)) 0) (sub1 i)]
                      [(= (remainder n (add1 i)) 0) (add1 i)]
                      [else (find-prime-iter n (+ i 6) maxd)]))
                (find-prime-iter n 6 (sqrt n))]))

(define (sum-prime-divisors n)
  (define smallest-prime-of-n (smallest-prime n))
  (if (= n 1)
  0
  (+ smallest-prime-of-n (sum-prime-divisors (quotient n smallest-prime-of-n)))))

;;; Задача 2

(define (pow x n)
  (if (= n 0)
  1
  (* x (pow x (sub1 n)))))

;;; Задача 3

(define (count-occurences d n)
  (cond [(= n 0) 0]
    [(= (remainder n 10) d)
       (add1 (count-occurences d (quotient n 10)))]
    [else (count-occurences d (quotient n 10))]))

;;; Задача 4

(define (ascending? n)
  (cond [(= n 0) #t]
        [(< (remainder n 10) (remainder (quotient n 10) 10)) #f]
        [else (ascending? (quotient n 10))]))

;;; Задача 5

(define (smallest-divisor n bigger-than)
  (define (calc-iter i)
  (if (= (remainder n i) 0)
    i
    (calc-iter (add1 i))))
  (calc-iter (add1 bigger-than)))

(define (perfect-number? n)
  (define (calc-iter current-divisor current-sum)
    (cond [(= current-divisor n) #f]
          [(= current-sum n) #t]
          [else (define divisor (smallest-divisor n current-divisor))
                (calc-iter divisor (+ current-sum divisor))]))
  (calc-iter 1 1))

;;; Задача 6

(define (calc-sum x n)
  (define (calc-iter i prev-powd sum)
  (define curr-powd (* prev-powd x))
  (if (= i n)
    sum
    (calc-iter (add1 i) curr-powd (+ sum curr-powd))))
  (calc-iter 0 1 1))