calculate the sum of proper divisors of a given number in Racket BSL

1.1k Views Asked by At

Design a Racket function named findProperDivisor that takes a natural number and calculates the sum of all its proper divisors. A proper divisor of a natural number is the divisor that is strictly less than the number.

Examples:

Input: 20

Output: 22

//Proper divisors: 1 + 2 + 4 + 5 + 10 = 22

(define (sum-of-proper-divisors n i)
  (cond [(= i 1) 1]
        [(= (remainder n i) 0)
         (+ i (sum-of-proper-divisors n (sub1 i)))]
        [else (sum-of-proper-divisors n (sub1 i))]))

I found this code on this page but it gives me 1+2+4+5+10+20=42 I need 22.

I would like to write this code with one parameter by using recursion and cond. I am using Beginning Student Language (BSL), which does not have things like let defined.

2

There are 2 best solutions below

0
On

Step 1: understand what the code is doing. Why is there an additional parameter? What is happening with it?

Step 2: How do you call this? What does this mean for i?

Step 3: What would you have to do differently so that the remainder is not checked against the number itself?

0
On

To fulfill the condition strictly smaller than itself, call it with (sum-of-proper-divisors 20 (sub1 20)) then you get 22, since then, 20 is not counted as divisor.

Since you should define that function with just one number as argument, - due to the constrains of this beginner-language, I would define the desired function as a second function:

(define (sum-of-proper-divisors n i)
  (cond ((= 1 i) 1)
        ((= (remainder n i) 0)
         (+ i (sum-of-proper-divisors n (sub1 i))))
        (else (sum-of-proper-divisors n (sub1 i)))))

(define (findProperDivisors n)
  (sum-of-proper-divisors n (sub1 n)))

(findProperDivisors 20) ;; => 22