Difference between revisions of "Euler problems/181 to 190"

From HaskellWiki
Jump to navigation Jump to search
((183) If we must have a solution here, let's at least have a decent one.)
Line 27: Line 27:
 
Solution:
 
Solution:
 
<haskell>
 
<haskell>
  +
-- Does the decimal expansion of p/q terminate?
pmax x a=a*(log x-log a)
 
  +
terminating p q = 1 == reduce [2,5] (q `div` gcd p q)
tofloat x=encodeFloat x 0
 
  +
where reduce [] n = n
fun x=
 
  +
reduce (x:xs) n | n `mod` x == 0 = reduce (x:xs) (n `div` x)
div n1 $gcd n1 x
 
  +
| otherwise = reduce xs n
where
 
  +
e=exp 1
 
  +
-- The expression (round $ fromIntegral n / e) computes the integer k
n=floor(fromInteger x/e)
 
  +
-- for which (n/k)^k is at a maximum.
n1=snd.maximum$[(b,a)|a<-[n..n+1],let b=pmax (tofloat x) (tofloat a)]
 
  +
answer = sum [if terminating n (round $ fromIntegral n / e) then -n else n
n `splitWith` p = doSplitWith 0 n
 
  +
| n <- [5 .. 10^4]]
where doSplitWith s t
 
 
where e = exp 1
| p `divides` t = doSplitWith (s+1) (t `div` p)
 
  +
| otherwise = (s, t)
 
  +
main = print answer
d `divides` n = n `mod` d == 0
 
funD x
 
|is25 k=(-x)
 
|otherwise =x
 
where
 
k=fun x
 
is25 x
 
|s==1=True
 
|otherwise=False
 
where
 
s=snd(splitWith (snd (splitWith x 2)) 5)
 
problem_183 =sum[funD a|a<- [5..10000]]
 
 
</haskell>
 
</haskell>

Revision as of 20:27, 24 February 2008

Problem 181

Investigating in how many ways objects of two different colours can be grouped.

Solution: This was my code, published here without my permission nor any attribution, shame on whoever put it here. Daniel.is.fischer

Problem 182

RSA encryption.

Solution:

fun a1 b1 =
    sum [ e |
    e <- [2..a*b-1],
    gcd e (a*b) == 1,
    gcd (e-1) a == 2,
    gcd (e-1) b == 2
    ]
    where
    a=a1-1
    b=b1-1
problem_182=fun 1009 3643

Problem 183

Maximum product of parts.

Solution:

-- Does the decimal expansion of p/q terminate?
terminating p q = 1 == reduce [2,5] (q `div` gcd p q)
        where reduce   []   n = n
              reduce (x:xs) n | n `mod` x == 0 = reduce (x:xs) (n `div` x)
                              | otherwise      = reduce xs n

-- The expression (round $ fromIntegral n / e) computes the integer k
-- for which (n/k)^k is at a maximum.
answer = sum [if terminating n (round $ fromIntegral n / e) then -n else n
                | n <- [5 .. 10^4]]
        where e = exp 1

main = print answer