21

When I do (/ 7 2), what should I do to get the result 3? If I do (/ 7 2.0), I get 3.5, which is as expected.

MatthewRock
  • 1,071
  • 1
  • 14
  • 30
appusajeev
  • 2,129
  • 3
  • 22
  • 20

4 Answers4

26
(floor 7 2)

Ref: http://rosettacode.org/wiki/Basic_integer_arithmetic#Common_Lisp

kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005
21

See FLOOR, CEILING and TRUNCATE in ANSI Common Lisp.

Examples (see the positive and negative numbers):

CL-USER 218 > (floor -5 2)
-3
1

CL-USER 219 > (ceiling -5 2)
-2
-1

CL-USER 220 > (truncate -5 2)
-2
-1

CL-USER 221 > (floor 5 2)
2
1

CL-USER 222 > (ceiling 5 2)
3
-1

CL-USER 223 > (truncate 5 2)
2
1

Usually for division to integer TRUNCATE is used.

Rainer Joswig
  • 136,269
  • 10
  • 221
  • 346
10

You can use the floor function:

(floor 7 2)
3
1

Note that it returns multiple values, and you only need the first one. Since floor returns multiple values, that can be done with multiple-value-bind as follows:

(multiple-value-bind (q r) (floor 7 2) q)
=> 3

Edit: As Rainer notes in his comment, you can just pass the result of floor as an argument if all you need is the quotient.

[1]> (floor 7 2)
3 ;
1
[2]> (+ (floor 7 2) 5)
8
[3]>

I'm leaving the reference to multiple-value-bind in the answer, since it's an important function to be familiar with.

Eli Bendersky
  • 263,248
  • 89
  • 350
  • 412
  • how do i get the first value? does it return a list?? – appusajeev Jan 16 '10 at 15:04
  • 4
    that's not needed. the first value is automatically passed to the next code. You need the MULTIPLE-VALUE-BIND if you want all values or some. (values (floor 7 2)) just returns the first. – Rainer Joswig Jan 16 '10 at 16:55
3

Use the floor function. In SBCL:

* (floor (/ 7 2))

3
1/2

Two values are returned, the integer part and the fractional part.

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285