[Haskell-cafe] How to decide if a number is an integer?
Daniel Fischer
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?
>
> 26
> 31
> 38
> 47
> 58
> 71
> 86
> 103
> 122
>
> IMO, the code works and your expectations are a bit off.
Quite.
*MMlouds> givenSum 11
[True,False,False,False,True,False,False,False,False,False,False]
The code tests whether a*a+2*(num+1) is a square, equivalently, whether there's a b such
that
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)]
[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29]
>
> Thomas
>
> 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
mailing list