[Haskell-cafe] How to decide if a number is an integer?
daniel.is.fischer at web.de
Tue Sep 29 07:32:53 EDT 2009
Am Dienstag 29 September 2009 09:02:19 schrieb Thomas DuBuisson:
> Unless I missed something, the function in question is:
> sqrt (a * a + 2 + 2 * num) - fromIntegral a
> where num = 10
> 1 -> sqrt (1 * 1 + 2 + 2 * 10) - 1 -> sqrt (1 + 2 + 20) - 1 -> sqrt
> (23) - 1 -> 3.79xxxxx
> the fractional will only ever come from the sqrt function. Do any of
> the following actually look like square values to you?
> IMO, the code works and your expectations are a bit off.
*MMlouds> givenSum 11
The code tests whether a*a+2*(num+1) is a square, equivalently, whether there's a b such
2*(num+1) == b^2 - a^2
Now, the difference of two squares is either odd or a multiple of 4.
2*(num+1) is never odd, so it must be a multiple of 4, i.e. num must be odd for any number
of the form a^2 + 2*(num+1) to be a square.
isIntegral x = snd (properFraction x) == 0
works for rational x and for small enough doubles/floats, but beware:
*MMlouds> [n | n <- [1 .. 100], not $ isIntegral (sqrt $ 4^n+222)]
> On Mon, Sep 28, 2009 at 11:54 PM, Magicloud Magiclouds
> <magicloud.magiclouds at gmail.com> wrote:
> > *Main> givenSum 10
> > [False,False,False,False,False,False,False,False,False,False]
More information about the Haskell-Cafe