Posts Tagged ‘python’

Project Euler Problem #243!

August 16th, 2010

Problem #243 says:

A positive fraction whose numerator is less than its denominator is called a proper fraction.
For any denominator, d, there will be d−1 proper fractions; for example, with d = 12:
1/12 , 2/12 , 3/12 , 4/12 , 5/12, 6/12 , 7/12 , 8/12 , 9/12 , 10/12 , 11/12 .

We shall call a fraction that cannot be cancelled down a resilient fraction.
Furthermore we shall define the resilience of a denominator, R(d), to be the ratio of its proper fractions that are resilient; for example, R(12) = 4/11 .
In fact, d = 12 is the smallest denominator having a resilience R(d) < 4/10 .

Find the smallest denominator d, having a resilience R(d) < 15499/94744 .


This is a problem where the answer came out of know where, I stared at it for a while then realized I have to minimize the euler totient. The simplest way to do that was to create a test number out of multiplying consecutive primes and going from there. So what the solution does is start with the first 5 prime numbers and multiplies them together then it steps through the a sequence from 1 to the last prime found. if it finds the number then it stops, else if goes till it hits a prime number bigger than the last one, multiplies the starting number by that prime and then starts back at 1 till it hits another prime or solves the problem.

Solution in python because that’s all I had when I came up with the answer, runs in well under a second.

def factor(n):
        if n == 1: return [1]
        i = 2
        limit = n**0.5
        while i <= limit:
                if n % i == 0:
                        ret = factor(n/i)
                        ret.append(i)
                        return ret
                i += 1
        return [n]  

def uniqify(seq):
        return list(set(seq))

def phi(x):
    t = x
    for k in uniqify(factor(x)):
        t -= t // k
    return t

def resilience(x):
    return phi(x) / (x-1.0)

lastprime = 11
base = 2*3*5*7*11.0
multiplier = 1.0
print "Starting value",  base

while (resilience(base * multiplier) > (15499.0/94744.0)):
    multiplier = multiplier +1.0
    if (multiplier > lastprime):
        if (len(factor(multiplier)) == 1):
            lastprime = multiplier
            base = base * multiplier
            print "New starting value for search",  base
            multiplier = 1.0

print "Answer :: ", base * multiplier

Tags: ,
Posted in Project Euler | Comments (0)

Project Euler Problem #132!

May 23rd, 2010

Problem #132 says:

A number consisting entirely of ones is called a repunit. We shall define R(k) to be a repunit of length k.

For example, R(10) = 1111111111 = 11×41×271×9091, and the sum of these prime factors is 9414.

Find the sum of the first forty prime factors of R(10^(9)).


To solve this problem we take the number and rearrange it a bit, then check for primes that fit the formula runs in about 12 seconds.

Solution in Python. Requires the RabinMiller.py file.

Problem132.py

from RabinMiller import *
from time import *

t0 = time()
def GeoSum (a,  n,  c):
    if (n == 1):
        return 1
    if (n==2):
        return (1+a)%c
    ret = ((GeoSum(a, n/2, c)%c)*((1+pow(a, n/2, c))%c))%c
    if (n&1):
        ret = (ret+pow(a, n-1, c))%c
    return ret

sum = 0
count = 0
i = 3
while (count <40):
    if (MillerRabin(i) and not GeoSum(10, 10**9,  i)):
        count = count + 1
        sum = sum + i
        print count, " divids by ", i
    i = i + 2
print sum
print time() - t0

RabinMiller.py

import sys
import random

def toBinary(n):
  r = []
  while (n > 0):
    r.append(n % 2)
    n = n / 2
  return r

def test(a, n):
  """
  test(a, n) -> bool Tests whether n is complex.

  Returns:
    - True, if n is complex.
    - False, if n is probably prime.
  """
  b = toBinary(n - 1)
  d = 1
  for i in xrange(len(b) - 1, -1, -1):
    x = d
    d = (d * d) % n
    if d == 1 and x != 1 and x != n - 1:
      return True # Complex
    if b[i] == 1:
      d = (d * a) % n
  if d != 1:
    return True # Complex
  return False # Prime

def MillerRabin(n, s = 3):
  """
    MillerRabin(n, s = 1000) -> bool Checks whether n is prime or not

    Returns:
      - True, if n is probably prime.
      - False, if n is complex.
  """
  for j in xrange(1, s + 1):
    a = random.randint(1, n - 1)
    if (test(a, n)):
      return False # n is complex
  return True # n is prime

Tags: ,
Posted in Project Euler | Comments (0)

Project Euler Problem #188!

November 19th, 2009

Problem #188 says:

The hyperexponentiation or tetration of a number a by a positive integer b, denoted by a↑↑b or ^(b)a, is recursively defined by: a↑↑1 = a, a↑↑(k+1) = a^((a↑↑k)). Thus we have e.g. 3↑↑2 = 3^(3) = 27, hence 3↑↑3 = 3^(27) = 7625597484987 and 3↑↑4 is roughly 10^(3.6383346400240996*10^12). Find the last 8 digits of 1777↑↑1855.

This problem rather basic when you think about it mathematically. And even simpler once you realize that python has a built in modulo parameter to its pow() function. Making this whole problem rather simple. And with a bit of poking around one realizes that you don’t have to go through the whole loop as the value we’re looking for appears in the first 20 loops through the program.
Anyway, Solution is in python (2.6).

def Tetrate(Base,Tetrate,Modulo):
    Value = 1
    while Tetrate:
        Value = pow(Base,Value,10**Modulo)
        Tetrate = Tetrate - 1
    return Value

print "Answer : ", Tetrate(1777,1855,8)

Tags: , ,
Posted in Project Euler | Comments (0)