DrRacket procedure body help (boolean-odd? x)

落花浮王杯 提交于 2019-12-13 10:09:59

问题


An iterative version of odd? for non-negative integer arguments can be written using and, or, and not. To do so, you have to take advantage of the fact that and and or are special forms that evaluate their arguments in order from left to right, exiting as soon as the value is determined. Write (boolean-odd? x) without using if or cond, but using and, or, not (boolean) instead. You may use + and -, but do not use quotient, remainder, /, etc.


回答1:


A number is even if two divides it evenly, and odd if there if there is a remainder of one. In general, when you divide a number k by a number n, the remainder is one element of the set {0,1,…n-1}. You can generalize your question by asking whether, when k is divided by n, the remainder is in some privileged set of remainder values. Since this is almost certainly homework, I do not want to provide a direct answer to your question, but I'll answer this more general version, without sticking to the constraints of using only and and or.

(define (special-remainder? k n special-remainders)
  (if (< k n)
      (member k special-remainders)
      (special-remainder? (- k n) special-remainders)))

This special-remainder? recursively divides k by n until a remainder less than n is found. Then n is tested for its specialness. In the case that you're considering, you'll be able to eliminate special-remainders, because you don't need (member k special-remainders). Since you only have one special remainder, you can just check whether k is that special remainder.




回答2:


A positive odd number can be defined as 1 + 2n. Thus an odd number is:

  • If x is 1
  • If x is greater than 1 and x-2 is odd.

Thus one* solution that is tail recursive/iterative looks like this:

(define (odd? x)
  (or (= ...)          ; #t if 1
      (and ...         ; #f if less than 1
           (odd? ...))); recurse with 2 less

*having played around with it it's many ways to do do this and still have it iterative and without if/cond.



来源:https://stackoverflow.com/questions/19281849/drracket-procedure-body-help-boolean-odd-x

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!