From e1ace4a36aa903411b6b623107e6d8d375bd252c Mon Sep 17 00:00:00 2001 From: Shlomi Fish Date: Mon, 16 Oct 2017 21:08:06 +0300 Subject: [PATCH] Add a faster version of Euler #97. It finishes in less than 0.1 seconds on my Core i3 machine with both the on-pypy python2.7 and python3. Based on: https://github.com/shlomif/project-euler/tree/master/project-euler/97 Does not require gmpy. --- 097/non-mersenne-faster.py | 62 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 097/non-mersenne-faster.py diff --git a/097/non-mersenne-faster.py b/097/non-mersenne-faster.py new file mode 100644 index 0000000..3c08dd5 --- /dev/null +++ b/097/non-mersenne-faster.py @@ -0,0 +1,62 @@ +#!/usr/bin/env python + +from six import print_ + +MOD = 10000000000 + + +def get_power_modulo(b, e): + if e == 0: + return 1 + + rec_p = get_power_modulo(b, (e >> 1)) + + ret = rec_p * rec_p + + if e & 0x1 != 0: + ret *= b + + return ret % MOD + + +def print_pow(b, e, msg): + result = get_power_modulo(b, e) + print_("%s : %d ** %d %% MOD = %d" % (msg, b, e, result)) + +print_pow(2, 5, "2 ** 5 is right.") + +print_pow(3, 3, "3 ** 3 is right.") + +print_pow(2, 10, "2 ** 10 == 1024 is right.") + +print_("Answer = ", + ((get_power_modulo(2, 7830457) * 28433 + 1) % MOD)) + +# Based on: +# https://github.com/shlomif/project-euler/tree/master/project-euler/97 +# +# Under the Expat licence. +# +# Copyright 2017 Shlomi Fish +# +# Permission is hereby granted, free of charge, to any person +# obtaining a copy of this software and associated documentation +# files (the "Software"), to deal in the Software without +# restriction, including without limitation the rights to use, +# copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the +# Software is furnished to do so, subject to the following +# conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +# OTHER DEALINGS IN THE SOFTWARE. +# --------------------------------------------------------------------------