Tag Archives: decimal

Euler Problem 197 – Convergent Functions

I solved this one kind of by accident. Its a short program (most things in Haskell are) and I coded it in just a few minutes. Then I plugged in a starting series of 10^6 numbers. Thought that would be a good start. Got the result in a few seconds, and figured that I would need to do the full 10^9 digits. Left it to work over the weekend. Of course, it never finished.

After analysing the function a little more, I discovered that its an oscillating convergent function. Interestingly, after only a few thousand numbers, the varience is smaller than 10^-9. So by using 10^6, it was already overkill.

f :: Double -> Double
f x = 
	let a = 30.403243784-(x**2)
	in fromIntegral (floor (2**a)) * 10**(-9)

u :: Double -> Double
u 0 = -1
u n = f ( u (n-1)) 

main =
	let n = 10^6
	in print $ (u n) + u(n+1)

Euler Problem 99

This was another easy one. Using natural logarithms, this routine runs very quickly (< 5 seconds). I also used the decimal class just in case I needed extra precision.

import psyco

import decimal
class Problem:
    def Solution(self):
        decimal.getcontext().prec = 50      
        P = []
        f = open("base_exp.txt", "r")
        for row in f.readlines():
            newRow = []
            for column in row.split(","):
        max = 0
        pos = 0
        for pair in P:
            v = decimal.Decimal(pair[1]*decimal.Decimal(pair[0]).ln()).exp()
            if v > max:
                max = v
                pos = P.index(pair)+1
            print P.index(pair)+1,
        return "\nAnswer = " + str(pos)
if __name__ == '__main__':
    P = Problem()
    print P.Solution()

Euler Problem 80

Python rocks. No surprise here. Its got a Decimal module that does everything. This routine runs inside of a second.

import decimal
from math import sqrt, floor
class Problem80:
    def __init__(self):
    def Solution(self):
        count = 0
        decimal.getcontext().prec = 110
        for n in range (1, 101):
            num = int(floor(sqrt(n)))
            text = str(decimal.Decimal(n).sqrt())[2:102]
            if len(text) == 100:
                count += num
                for i in range (0,99):
                    count += int(text[i])
            print n,count
        return "Answer = " + str(count)
if __name__ == '__main__':
    P = Problem80()
    print P.Solution()