Get the Sum of given number in scheme - scheme

Hi i want my function to sum digits such that the result is less than 10 (77 = 14=5). dont know why it's passing the base case
(define (reduct n)
(if(< n 10) n
(+(modulo n 10)(reduct (truncate(/ n 10))))))

You forgot to call reduct again after adding. Here's the fixed version:
(define (reduct n)
(if (< n 10)
n
(reduct (+ (modulo n 10) (reduct (quotient n 10))))))
Note that the inner reduct recursion is actually redundant and can be removed, leaving:
(define (reduct n)
(if (< n 10)
n
(reduct (+ (modulo n 10) (quotient n 10)))))
or, if you want to only divide once (and get the modulo too), you can use the R7RS floor/ procedure:
(define (reduct n)
(if (< n 10)
n
(reduct (call-with-values (lambda () (floor/ n 10)) +))))
(This is, by the way, a pure loop. A Ruby version could look like:
def reduct(n)
n = n % 10 + n / 10 while n >= 10
n
end
or (for the one-division-only approach)
def reduct(n)
n = n.divmod(10).reduce(:+) while n >= 10
n
end
except that it uses mutation unlike the Scheme version.)
However, as my comment already says, the result will always be the same as doing (modulo n 9) (except that 0 should become 9, so (+ (modulo (- n 1) 9) 1) is probably more correct), so if you're doing this for numerological purposes or otherwise not a homework which requires you to do it the "hard way", just use that.

Related

Knuth-Morris-Pratt algorithm in Scheme

This is the code to calculate the failure function (how many steps we have to go back) in Scheme, when we use the Knuth-Morris-Pratt algorithm:
(define (compute-failure-function p)
(define n-p (string-length p))
(define sigma-table (make-vector n-p 0))
(let loop
((i-p 2)
(k 0))
(cond
((>= i-p n-p)
(vector-set! sigma-table (- n-p 1) k))
((eq? (string-ref p k)
(string-ref p (- i-p 1)))
(vector-set! sigma-table i-p (+ k 1))
(loop (+ i-p 1) (+ k 1)))
((> k 0)
(loop i-p (vector-ref sigma-table k)))
(else ; k=0
(vector-set! sigma-table i-p 0)
(loop (+ i-p 1) k))))
(vector-set! sigma-table 0 -1)
(lambda (q)
(vector-ref sigma-table q)))
But I do not understand the part when k > 0. Can someone explain it please?
I see you're confused with the syntax of a named let. This post does a good job explaining how it works, but perhaps an example with more familiar syntax will make things clearer. Take this code in Python, it adds all integers from 1 to 10:
sum = 0
n = 1
while n <= 10:
sum += n
n += 1
print(sum)
=> 55
Now let's try to write it in a recursive fashion, I'll call my function loop. This is completely equivalent:
def loop(n, sum):
if n > 10:
return sum
else:
return loop(n + 1, n + sum)
loop(1, 0)
=> 55
In the above example, the loop function implements an iteration, the parameter n is used to keep track of the current position, and the parameter sum accumulates the answer. Now let's write the exact same code, but in Scheme:
(let loop ((n 1) (sum 0))
(cond ((> n 10) sum)
(else (loop (+ n 1) (+ n sum)))))
=> 55
Now we've defined a local procedure called loop which is then automatically called with the initial values 1 and 0 for its parameters n and sum. When the base case of the recursion is reached, we return sum, otherwise we keep calling this procedure, passing updated values for the parameters. It's exactly the same as in the Python code! Don't be confused by the syntax.
In your algorithm, i-p and k are the iteration variables, which are initialized to 2 and 0 respectively. Depending on which condition is true, the iteration continues when we call loop again with updated values for i-p and k, or it ends when the case (>= i-p n-p) is reached, at this point the loop exits and the computed value is in the variable sigma-table. The procedure ends by returning a new function, referred to as the "failure function".

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

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.
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?
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

SICP exercise 1.28: false negatives in the Miller-Rabin test

Exercise 1.28. One variant of the Fermat test that cannot be fooled is called the Miller-Rabin test (Miller 1976; Rabin 1980). This
starts from an alternate form of Fermat's Little Theorem, which states
that if n is a prime number and a is any positive integer less than n,
then a raised to the (n - 1)st power is congruent to 1 modulo n. To
test the primality of a number n by the Miller-Rabin test, we pick a
random number a < n and raise a to the (n - 1)st power modulo n using
the expmod procedure. However, whenever we perform the squaring step
in expmod, we check to see if we have discovered a ''nontrivial square
root of 1 modulo n,'' that is, a number not equal to 1 or n - 1 whose
square is equal to 1 modulo n. It is possible to prove that if such a
nontrivial square root of 1 exists, then n is not prime. It is also
possible to prove that if n is an odd number that is not prime, then,
for at least half the numbers a < n, computing a^(n-1) in this way will
reveal a nontrivial square root of 1 modulo n. (This is why the
Miller-Rabin test cannot be fooled.) Modify the expmod procedure to
signal if it discovers a nontrivial square root of 1, and use this to
implement the Miller-Rabin test with a procedure analogous to
fermat-test. Check your procedure by testing various known primes and
non-primes. Hint: One convenient way to make expmod signal is to have
it return 0.
(define (fast-prime? n)
(define (fast-prime-iter n counter)
(cond ((= counter 1) #t) ; There is no need to check 1
((miller-rabin-test n counter)
(fast-prime-iter n (- counter 1)))
(else
(newline)
(display counter)
#f)))
(fast-prime-iter n (- n 2)))
(define (miller-rabin-test n a)
(define (expmod base exp m)
(cond ((= exp 0) 1)
((even? exp)
(nontrivial-square-root?
(remainder (square (expmod base (/ exp 2) m))
m)))
(else
(remainder (* base (expmod base (- exp 1) m))
m))))
(= (expmod a (- n 1) n) 1))
(define (nontrivial-square-root? val)
(if (= val 1)
0
val))
My idea is to filter out those so-called "nontrivial square roots of 1 modulo n" with the procedure nontrivial-square-root?. A 0 is returned if (remainder (square (expmod base (/ exp 2) m)) m) is 1, in which case the square of (expmod base (/ exp 2) m) must be equal to 1 modulo n (this is because m always equals n), making it a nontrivial square root.
While nontrivial-square-root? does filter out carmichael numbers such as 561, 1105, 1729, 2465, 2821 and 6601, prime numbers such as 7 and 13 are also reported to be composite.
What causes these false negatives?
The important part of the quote marked with bold text:
However, whenever we perform the squaring step in expmod, we check to see if we have discovered a ''nontrivial square root of 1 modulo n,'' that is, a number not equal to 1 or n - 1 whose square is equal to 1 modulo n
So before you square and take the remainder you have to check that the argument is not 1 or n - 1. This occurs, e.g., if you call (miller-rabin-test 5 3). Working the recursion out you notice that there is a call (nontrivial-square-root? (remainder (square 4) 5)) which evaluates to (nontrivial-square-root? 1). However, 5 can still be prime because 4 is 5 - 1.
So in the squaring part you can, e.g., call a following function:
(define (sqrmod-with-check val n)
(let ((sqrmod (remainder (square val) n)))
(cond ((or (= val (- n 1)) (= val 1)) sqrmod)
((= sqrmod 1) 0)
(else sqrmod))))
where the arguments are the expmod call and m. This does the square and remainder for you except in the case we have found a nontrivial square root of 1 modulo n, when it returns 0. I divided it to three conditions, instead of two, just because of readability.

Different ways to calculate number

I need to write a function that will return the number of ways in which can be n (n is a natural number) written as the sum of natural numbers.
For example: 4 can be written as 1+1+1+1, 1+1+2, 2+2, 3+1 and 4.
I have written a function that returns the number of all the options, but does not take into account that the possibilities 1 + 1 + 2 and 2 + 1 + 1 (and all similar cases) are equal. So for n=4 it returns 8 instead of 5.
Here is my function:
(define (possibilities n)
(define (loop i)
(cond [(= i n) 1]
[(> i n) 0]
[(+ (possibilities (- n i)) (loop (+ i 1)))]))
(cond [(< n 1) 0]
[#t (loop 1)]))
Could you please help me with fixing my function, so it will work the way it should be. Thank you.
This is a well-known function, it's called the partition function P, its possible values are referenced as A000041 in the on-line encyclopedia of integer sequences.
One simple solution (not the fastest!) would be to use this helper function, which denotes the number of ways of writing n as a sum of exactly k terms:
(define (p n k)
(cond ((> k n) 0)
((= k 0) 0)
((= k n) 1)
(else
(+ (p (sub1 n) (sub1 k))
(p (- n k) k)))))
Then we just have to add the possible results, being careful with the edge cases:
(define (possibilities n)
(cond ((negative? n) 0)
((zero? n) 1)
(else
(for/sum ([i (in-range (add1 n))])
(p n i)))))
For example:
(map possibilities (range 11))
=> '(1 1 2 3 5 7 11 15 22 30 42)

Sort prime factors in ascending order Scheme

I am new to Scheme and I want to sort the prime factors of a number into ascending order. I found this code, but it does not sort.
(define (primefact n)
(let loop ([n n] [m 2] [factors (list)])
(cond [(= n 1) factors]
[(= 0 (modulo n m)) (loop (/ n m) 2 (cons m factors))]
[else (loop n (add1 m) factors)])))
Can you please help.
Thank you
I would say it sorts, but descending. If you want to sort the other way, just reverse the result:
(cond [(= n 1) (reverse factors)]
Usually when you need something sorted in the order you get them you can
cons them like this:
(define (primefact-asc n)
(let recur ((n n) (m 2))
(cond ((= n 1) '())
((= 0 (modulo n m)) (cons m (recur (/ n m) m))) ; replaced 2 with m
(else (recur n (+ 1 m))))))
Note that this is not tail recursive since it needs to cons the result, but since the amount of factors in an answer is few (thousands perhaps) it won't matter much.
Also, since it does find the factors in order you don't need to start at 2 every round but the number you found.
Which dialect of Scheme is used?
Three hints:
You need only to test for divisors less equal as the square-root of your Number.
a * b = N ; a < b ---> a <= sqrt( N ).
If you need all Prime-Numbers less some Number, you should use the sieve of eratothenes. See Wikipedia.
Before you start to write a program, look in Wikipedia.
If

Resources