Beispiel #1
0
def siemens_B(alpha, beta, x1, y1, z1, R0):
    ''' Calculate displacement field from Siemens coefficients
    '''
    nmax = alpha.shape[0] - 1
    x1 = x1 + 0.0001  # hack to avoid singularities at R=0

    # convert to spherical coordinates
    r = np.sqrt(x1 * x1 + y1 * y1 + z1 * z1)
    theta = np.arccos(z1 / r)
    phi = np.arctan2(y1 / r, x1 / r)

    b = np.zeros(x1.shape)
    for n in xrange(0, nmax + 1):
        f = np.power(r / R0, n)
        for m in xrange(0, n + 1):
            f2 = alpha[n, m] * np.cos(m * phi) + beta[n, m] * np.sin(m * phi)
            _ptemp = utils.legendre(n, m, np.cos(theta))
            #_ptemp = scipy.special.lpmv(m, n, np.cos(theta))
            normfact = 1
            # this is Siemens normalization
            if m > 0:
                normfact = math.pow(-1, m) * \
                math.sqrt(float((2 * n + 1) * factorial(n - m)) \
                          / float(2 * factorial(n + m)))
            _p = normfact * _ptemp
            b = b + f * _p * f2
    return b
def siemens_B(alpha, beta, x1, y1, z1, R0):
    ''' Calculate displacement field from Siemens coefficients
    '''
    nmax = alpha.shape[0] - 1
    x1 = x1 + 0.0001  # hack to avoid singularities at R=0

    # convert to spherical coordinates
    r = np.sqrt(x1 * x1 + y1 * y1 + z1 * z1)
    theta = np.arccos(z1 / r)
    phi = np.arctan2(y1 / r, x1 / r)

    b = np.zeros(x1.shape)
    for n in xrange(0, nmax + 1):
        f = np.power(r / R0, n)
        for m in xrange(0, n + 1):
            f2 = alpha[n, m] * np.cos(m * phi) + beta[n, m] * np.sin(m * phi)
            _ptemp = utils.legendre(n, m, np.cos(theta))
            #_ptemp = scipy.special.lpmv(m, n, np.cos(theta))
            normfact = 1
            # this is Siemens normalization
            if m > 0:
                normfact = math.pow(-1, m) * \
                math.sqrt(float((2 * n + 1) * factorial(n - m)) \
                          / float(2 * factorial(n + m)))
            _p = normfact * _ptemp
            b = b + f * _p * f2
    return b
Beispiel #3
0
def p34():
    target = factorial(9) * 7
    digit_fact = [factorial(i)for i in range(0, 10)]
    result = 0
    for num in range(4, target):
        sum_of_fact = sum([digit_fact[int(digit)]
            for digit in str(num)])

        if sum_of_fact != num:
            continue
        result += sum_of_fact
    return result
def run():
    num = 20
    max = utils.factorial(num)

    for x in xrange(num, max + 1):
        if not any([y for y in range(1, num + 1) if x % y != 0]):
            print x
            break
Beispiel #5
0
def _calc_fact_term(m, n, dn, s, eta):
    denom1 = 2 * s + 1
    denom2 = denom1 + dn
    denom3 = m - 2 * s
    if denom3 > denom1:
        tmp = denom1
        denom1 = denom3
        denom3 = tmp
    if m > denom1:
        num = permutation(n, denom1) * permutation(m, denom1)
        denom = factorial(denom2)**2 * factorial(denom3)**2
    else:
        num = permutation(n, denom1)
        denom = (permutation(denom1, m) * factorial(denom2)**2 *
                 factorial(denom3)**2)
    res = sqrt(num / denom)
    return res
Beispiel #6
0
def test_profiler():
    profiler = TracingProfiler(top_frames=[sys._getframe()])
    assert isinstance(profiler.stats, RecordingStatistics)
    stats, cpu_time, wall_time = profiler.result()
    assert len(stats) == 0
    with profiler:
        factorial(1000)
        factorial(10000)
    stats1 = find_stats(profiler.stats, 'factorial')
    stats2 = find_stats(profiler.stats, '__enter__')
    stats3 = find_stats(profiler.stats, '__exit__')
    assert stats1.deep_time != 0
    assert stats1.deep_time == stats1.own_time
    assert stats1.own_time > stats2.own_time
    assert stats1.own_time > stats3.own_time
    assert stats1.own_hits == 2
    assert stats2.own_hits == 0  # entering to __enter__() wasn't profiled.
    assert stats3.own_hits == 1
Beispiel #7
0
def test_profiler():
    profiler = TracingProfiler(top_frames=[sys._getframe()])
    assert isinstance(profiler.stats, RecordingStatistics)
    stats, cpu_time, wall_time = profiler.result()
    assert len(stats) == 0
    with profiler:
        factorial(1000)
        factorial(10000)
    stats1 = find_stats(profiler.stats, 'factorial')
    stats2 = find_stats(profiler.stats, '__enter__')
    stats3 = find_stats(profiler.stats, '__exit__')
    assert stats1.deep_time != 0
    assert stats1.deep_time == stats1.own_time
    assert stats1.own_time > stats2.own_time
    assert stats1.own_time > stats3.own_time
    assert stats1.own_hits == 2
    assert stats2.own_hits == 0  # entering to __enter__() wasn't profiled.
    assert stats3.own_hits == 1
def test_profiler():
    profiler = Profiler(top_frame=sys._getframe())
    assert isinstance(profiler.stats, RecordingStatistics)
    assert isinstance(profiler.result(), FrozenStatistics)
    assert len(profiler.stats) == 0
    with profiling(profiler):
        factorial(1000)
        factorial(10000)
    stat1 = find_stat(profiler.stats, 'factorial')
    stat2 = find_stat(profiler.stats, '__enter__')
    stat3 = find_stat(profiler.stats, '__exit__')
    assert stat1.total_time != 0
    assert stat1.total_time == stat1.own_time
    assert stat1.own_time > stat2.own_time
    assert stat1.own_time > stat3.own_time
    assert stat1.calls == 2
    assert stat2.calls == 0  # entering to __enter__() wasn't profiled.
    assert stat3.calls == 1
Beispiel #9
0
def test_profiler():
    profiler = Profiler(top_frame=sys._getframe())
    assert isinstance(profiler.stats, RecordingStatistics)
    assert isinstance(profiler.result(), FrozenStatistics)
    assert len(profiler.stats) == 0
    with profiling(profiler):
        factorial(1000)
        factorial(10000)
    stat1 = find_stat(profiler.stats, 'factorial')
    stat2 = find_stat(profiler.stats, '__enter__')
    stat3 = find_stat(profiler.stats, '__exit__')
    assert stat1.total_time != 0
    assert stat1.total_time == stat1.own_time
    assert stat1.own_time > stat2.own_time
    assert stat1.own_time > stat3.own_time
    assert stat1.calls == 2
    assert stat2.calls == 0  # entering to __enter__() wasn't profiled.
    assert stat3.calls == 1
Beispiel #10
0
def curiousNumber(num):
    l = list(map(int, str(num)))
    sum = 0
    for i in l:
        sum += factorial(i)

    if (num == sum):
        return True
    else:
        return False
Beispiel #11
0
def main():
    factorials = [utils.factorial(i) for i in range(10)]
    upper_limit = sum(factorials) + 1

    summation = 0

    for i in range(3, upper_limit):
        if factorial_digits(i, factorials) == i:
            summation += i

    return summation
Beispiel #12
0
def num_permutations(l):
    """returns the number of permutations possible from iterable l. Copied from 74, with fixes"""
    counts = defaultdict(int)
    for i in l:
        counts[i] += 1
    
    # Can't have leading digit 0
    invalid = 0
    if 0 in counts:
        n = list(l)
        n.remove(0) # just get rid of one
        invalid = num_permutations(['A' if i == 0 else i for i in n])
    
    return factorial(len(l)) / reduce(operator.mul, map(factorial, counts.values()), 1) - invalid
Beispiel #13
0
def main(NUMBERS, TARGET):

    n = len(NUMBERS)

    progress = 0
    solutionsGiven = 0
    SOL_SPACE_SIZE = n * (factorial(n - 1)**2) * (2**(n - 1)
                                                  )  # See attached PDF

    countdown.spinner(NUMBERS, TARGET)

    INDENT = "\t\t\t"

    with open("solutions.txt", "w") as file:
        solution_generator = solver(NUMBERS, TARGET)

        for solution in solution_generator:
            progress += 1

            if solution != "":

                if solutionsGiven <= 100:
                    file.write(solution + "\n")
                    solutionsGiven += 1
                progressFractional = progress / SOL_SPACE_SIZE

                countdown.spinner(NUMBERS, TARGET)
                progressBar(INDENT, progressFractional, solution)
        #   Uncomment line below to see number of operations that ran.
        #   This number is exactly equal to the solution
        #   space calculated!
        # file.write(str(progress))

    with open("solutions.txt", "r") as file:

        solutions = file.readlines()

        if solutions == []:
            print("This problem is impossible!")
            return

        [print(line) for line in solutions[:100]]
Beispiel #14
0
def run():
    """
    Solution: Brute force search with a heuristic upper bound.

    What's the largest number beyond which this property cannot hold?

    I don't know enough number theory to procure a tight bound, but we can get
    one that's computationally good enough.

    Heuristic: Since every digit can at most contribute 9! = 362880 to the sum,
    beyond 6 digits the fac sum becomes increasingly unlikely to match the
    magnitude of the number since every additional digit only adds a relatively
    small 6 digit number to the sum.
    """
    N = 100000
    total = 0

    for n in xrange(3, N):
        if sum(map(lambda x: factorial(int(x)), str(n))) == n:
            total += n

    # sidenote: it turns out that only one other number besides the example
    #fits the given criteria.
    return total
Beispiel #15
0
from utils import factorial

print(sum(map(int, list(str(factorial(100))))))
Beispiel #16
0
def factorialDigitSum(n):
    fact = factorial(n)
    return sumDigit(fact)
Beispiel #17
0
# How many chains, with a starting number below one million, contain exactly sixty non-repeating terms?

# brute force? ok!
import sys
sys.path.append('../utils')
sys.path.append('utils')
from utils import factorial

fact_dict = {0:1}
for k in range(1,10):
    fact_dict[k] = factorial(k)

def digit_wise_factorial(n):
    return(sum([fact_dict[int(x)] for x in str(n)]))

stopping_criteria = {}
stopping_criteria[169] = [363601, 1454]
stopping_criteria[363601] = [1454, 169]
stopping_criteria[1454] = [363601, 169]
stopping_criteria[871] = [45361]
stopping_criteria[45361] = [871]
stopping_criteria[872] = [45362]
stopping_criteria[45362] = [872]

chain_of_60 = 0
for x in range(10,1000000):
    if x % 10000 == 0:
        print('workig on: ' + str(x))
    y = x
    chain = set()
    while y not in chain:
Beispiel #18
0
 def solve(self):
     sum = 0
     strValue = str(factorial(self.num))
     for item in strValue:
         sum += int(item)
     return sum
Beispiel #19
0
Datei: p53.py Projekt: nh13/euler
def n_C_r(n, r, fact):
    return factorial(fact, n) / (factorial(fact, r) * factorial(fact, (n-r))) 
Beispiel #20
0
#
# Solution to Project Euler Problem 34
#

import utils

for i in range(3, 9999999):
    if sum([utils.factorial(int(x)) for x in str(i)]) == i:
        print(i)
Beispiel #21
0
def ncr(n, r):
    return factorial(n) / (factorial(r) * factorial(n-r))
Beispiel #22
0
 def heavy():
     factorial(10000)
Beispiel #23
0
from utils import factorial

print(sum([int(d) for d in str(next(factorial(100)))]))
Beispiel #24
0
 def light():
     factorial(10)
     sleep(0.1)
     factorial(10)
Beispiel #25
0
def factorialDigitSum(n):
    fact = factorial(n)
    return sumDigit(fact)
Beispiel #26
0
def run_factorial():
    assert_true(utils.factorial(5), 120, 'Factorial 5')
Beispiel #27
0
def count_lattice_path(n, m):
    return factorial(n + m) // (factorial(n) * factorial(m))
Beispiel #28
0
def main():
    factorial = utils.factorial(100)
    return sum(int(s) for s in str(factorial))
# n! means n x (n - 1) x ... x 3 x 2 x 1
#
# For example, 10! = 10 x 9 x ... x 3 x 2 x 1 = 3628800,
# and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
#
# Find the sum of the digits in the number 100!

import time

from utils import factorial


if __name__ == '__main__':
    t0 = time.time()

    value = str(factorial(100))
    result = 0

    for c in value:
        result += int(c)

    runtime = time.time() - t0

    print 'Result = {}'.format(result)
    print 'Runtime = {}'.format(runtime)
Beispiel #30
0
def problem_020(n: int = 100) -> int:
    """
    Straightforward solution.
    """
    return sum_of_digits_in_number(factorial(n))
Beispiel #31
0
def run():
    """
    Pretty straight forward. Python saves the day again.
    """
    return sum(map(int, str(factorial(100))))
# n! means n x (n - 1) x ... x 3 x 2 x 1
#
# For example, 10! = 10 x 9 x ... x 3 x 2 x 1 = 3628800,
# and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
#
# Find the sum of the digits in the number 100!

import time

from utils import factorial

if __name__ == '__main__':
    t0 = time.time()

    value = str(factorial(100))
    result = 0

    for c in value:
        result += int(c)

    runtime = time.time() - t0

    print 'Result = {}'.format(result)
    print 'Runtime = {}'.format(runtime)
Beispiel #33
0
def comb(n,k):
    return factorial(n)/(factorial(k)*factorial(n-k))
Beispiel #34
0
def e20():
    return sum(int(c) for c in str(factorial(100)))
Beispiel #35
0
 def _operation(self, x, y):
     return factorial(x)
Beispiel #36
0
 def light():
     factorial(10)
     sleep(0.1)
     factorial(10)
Beispiel #37
0
"""
Project Euler Problem 15
========================

Starting in the top left corner of a 2 * 2 grid, there are 6 routes
(without backtracking) to the bottom right corner.

How many routes are there through a 20 * 20 grid?
"""

# The number of "North-East" paths through a lattice from (0,0) to (x,y) is
# [https://en.wikipedia.org/wiki/Lattice_path]
# the number of combinations of 'a' objects out of a set of 'a + b' objects,
# i.e.
#   / x + y \   (x + y)!
#   |       | = -------
#   \   x   /    (x!)^2
#
# In the case of a square grid:
#
#   /  2x  \   (2x)!
#   |      | = -------
#   \   x  /    2 * x!

from utils import factorial

GRIDSIZE = 20

routes = factorial(2 * GRIDSIZE) / ((factorial(GRIDSIZE)) ** 2)
print routes
Beispiel #38
0
def run_factorial():
    assert_true(utils.factorial(5), 120, 'Factorial 5')
Beispiel #39
0
from utils import factorial, sum_digits

print(sum_digits(factorial(100)))
Beispiel #40
0
 def heavy():
     factorial(10000)
Beispiel #41
0
Datei: p53.py Projekt: icot/euler
def comb(n,r):
    return factorial(n)/(factorial(n-r)*factorial(r))
Beispiel #42
0
from utils import factorial

strFac = str( factorial(100) )
digitTotal = 0

for c in strFac:
    digitTotal += int(c)

if __name__ == '__main__':
    print digitTotal
Beispiel #43
0
import pyperclip
from utils import factorial
import pyinputplus as pyip

num = pyip.inputInt(prompt="Enter a number:   ")

factorial_num = factorial(num)
print(factorial_num)
pyperclip.copy(factorial_num)

print("Factorial Copied to Clipboard")