Example #1
0
    def run(self):
        if len(sys.argv) == 1:
            print('======= Z_n STRUCTURE EMULATOR =======\n')

            while True:
                n = self.input_int('Let n = ', 'Sorry! Please input an integer n >= 2...', ZN_COND_N)
                self.zn = Zn(n)

                a = self.input_int('Please input a number "a" to calculate: ', 'Sorry! Please input a valid integer...')
                self.a = self.zn.consider(a)

                b = self.input_int('And a second number "b": ', 'Sorry! Please input a valid integer...')
                self.b = self.zn.consider(b)

                if not self.exec():
                    return
   
        else:
            parser = ap.ArgumentParser(description = 'Z_n STRUCTURE EMULATOR', epilog = 'Demonstrating calculations e.g. +, -, *, finding multiplicative inverse, and fast modular exponentiation!\n')
            parser.add_argument('n', action = 'store', type = int, help = 'Base n for Z_n structure')
            parser.add_argument('a', action = 'store', type = int, help = 'A number to calculate')
            parser.add_argument('b', action = 'store', type = int, help = 'And a second number')

            try:
                args = parser.parse_args()
            except:
                parser.print_help()
                return

            if not ZN_COND_N(args.n):
                print('ERROR: n must be >= 2! Exitting...')
            else:
                self.zn = Zn(args.n)
                self.a, self.b = self.zn.consider(args.a), self.zn.consider(args.b)
                self.exec(False)
Example #2
0
 def setUp(self):
     self.z2 = Zn(2)
     self.z3 = Zn(3)
     self.z10 = Zn(10)
     self.z11 = Zn(11)
     self.z100 = Zn(100)
     self.z101 = Zn(101)
     self.t2 = Zn.TableFormat(2, self.z2.add, range(2), "+")
     self.t3 = Zn.TableFormat(3, self.z3.add, range(3), "+")
     self.t10 = Zn.TableFormat(10, self.z10.add, range(10), "+")
     self.t11 = Zn.TableFormat(11, self.z11.add, range(11), "+")
     self.t100 = Zn.TableFormat(100, self.z100.add, range(100), "+")
     self.t101 = Zn.TableFormat(101, self.z101.add, range(101), "+")
Example #3
0
def process():
    fin = open(FIN, 'r')
    fout = open(FOUT, 'w')

    bits = [int(bit) for bit in next(fin).split(' ') if bit != '\n']
    n_samples = int(next(fin))
    ns = [int(n) for n in next(fin).split(' ') if n != '\n']
    total = n_samples * len(bits) * len(ns)

    ints = []
    for line in fin:
        a, b = [int(num) for num in line.split(' ')]
        ints.append((a, b))

    running_times = []
    with alive_bar(total) as bar:
        for n in ns:
            print('----- In Z_{} -----'.format(n))
            zn = Zn(n)
            mib = []
            mie = []
            me = []

            for a, b in ints:
                res, res_time = process_sample(zn.consider(a), zn.consider(b))
                res += res_time
                for r in res:
                    fout.write('%s ' % r)
                fout.write('\n')
                mib.append(res_time[0])
                mie.append(res_time[1])
                me.append(res_time[2])
                bar()

            sums = [0, 0, 0]
            for i in range(len(mib)):
                sums[0] += mib[i]
                sums[1] += mie[i]
                sums[2] += me[i]

                if i % n_samples == n_samples - 1:
                    avgs = [s / n_samples for s in sums]
                    for avg in avgs:
                        fout.write('%s ' % avg)
                    fout.write('\n')
                    sums = [0, 0, 0]

            fout.write('------------------------\n')

    fin.close()
    fout.close()
Example #4
0
class TestZn(unittest.TestCase):

    def setUp(self):
        self.z2 = Zn(2)
        self.z3 = Zn(3)
        self.z10 = Zn(10)
        self.z11 = Zn(11)
        self.z100 = Zn(100)
        self.z101 = Zn(101)
        self.t2 = Zn.TableFormat(2, self.z2.add, range(2), "+")
        self.t3 = Zn.TableFormat(3, self.z3.add, range(3), "+")
        self.t10 = Zn.TableFormat(10, self.z10.add, range(10), "+")
        self.t11 = Zn.TableFormat(11, self.z11.add, range(11), "+")
        self.t100 = Zn.TableFormat(100, self.z100.add, range(100), "+")
        self.t101 = Zn.TableFormat(101, self.z101.add, range(101), "+")

    def test_z2_str(self):
        result = self.z2.__str__()
        self.assertEqual(result, """Z2
 +| 0 1  *| 1
--+---- --+--
 0| 0 1  1| 1
 1| 1 0 """)

    def test_init_error(self):
        Zn(2)
        self.assertRaises(ValueError, Zn, 1)
        
    def test_col_width(self):
        self.assertEqual(self.t2.col_width(), 2)
        self.assertEqual(self.t10.col_width(), 2)
        self.assertEqual(self.t11.col_width(), 3)
        self.assertEqual(self.t100.col_width(), 3)
        self.assertEqual(self.t101.col_width(), 4)

    def test_cap_data(self):
        self.assertEqual(Zn.Cap(self.t2).data(), " 0/ 1".split("/"))
        self.assertEqual(Zn.Cap(self.t3).data(), " 0/ 1/ 2".split("/"))

    def test_data_data(self):
        self.assertEqual(Zn.Data(1, self.t2).data(), " 1/ 0".split("/"))
        self.assertEqual(Zn.Data(2, self.t3).data(), " 2/ 0/ 1".split("/"))
        
    def test_cap(self):
        self.assertEqual(Zn.StringTable(self.t2).cap(), " +| 0 1")
        self.assertEqual(Zn.StringTable(self.t10).cap(), " +| 0 1 2 3 4 5 6 7 8 9")
        self.assertEqual(Zn.StringTable(self.t11).cap(), "  +|  0  1  2  3  4  5  6  7  8  9 10")

    def test_data(self):
        self.assertEqual(Zn.Data(1, self.t2).output(), " 1/|/ 1/ 0".split("/"))
        self.assertEqual(Zn.Data(2, self.t3).output(), " 2/|/ 2/ 0/ 1".split("/"))

    def test_sep(self):
        self.assertEqual(Zn.StringTable(self.t2).sep(), "--+----")
        self.assertEqual(Zn.StringTable(self.t3).sep(), "--+------")

    def test_str_multi2(self):
        self.assertEqual(self.z2.str_multi_table(), \
""" *| 1
--+--
 1| 1""".split("\n"))
        
    def test_str_multi3(self):
        self.assertEqual(self.z3.str_multi_table(), \
""" *| 1 2
--+----
 1| 1 2
 2| 2 1""".split("\n"))
        
    def test_str_add2(self):
        self.assertEqual(self.z2.str_add_table(), \
""" +| 0 1
--+----
 0| 0 1
 1| 1 0""".split("\n"))

    def test_str_add3(self):
        self.assertEqual(self.z3.str_add_table(), \
""" +| 0 1 2
--+------
 0| 0 1 2
 1| 1 2 0
 2| 2 0 1""".split("\n"))
        
    def test_mul(self):
        self.assertEqual(self.z3.mul(2, 1), 2)
        self.assertEqual(self.z3.mul(2, 2), 1)
        self.assertEqual(self.z3.mul(2, 3), 0)

    def test_add(self):
        self.assertEqual(self.z3.add(2, 1), 0)
        self.assertEqual(self.z3.add(2, 2), 1)
        
    def test_tableformat_op(self):
        self.assertEqual(self.t3.op(2, 1), 0)
        self.assertEqual(self.t3.op(2, 2), 1)
Example #5
0
class ConsoleUI():
    """ Managing user inputs and outputs via the command line

    run():  start running the program in the command line

    * Other functions are only for internal uses!
    """
    def __init__(self):
        pass

    def input_int(self, msg, err_msg, cond = lambda x: True):
        while True:
            try:
                x = float(input(msg))
                x = int_check_strict(x, None, cond)
            except ValueError:
                print(err_msg)
                continue
            else:
                print('--- Received: {}'.format(x))
                return x

    def run(self):
        if len(sys.argv) == 1:
            print('======= Z_n STRUCTURE EMULATOR =======\n')

            while True:
                n = self.input_int('Let n = ', 'Sorry! Please input an integer n >= 2...', ZN_COND_N)
                self.zn = Zn(n)

                a = self.input_int('Please input a number "a" to calculate: ', 'Sorry! Please input a valid integer...')
                self.a = self.zn.consider(a)

                b = self.input_int('And a second number "b": ', 'Sorry! Please input a valid integer...')
                self.b = self.zn.consider(b)

                if not self.exec():
                    return
   
        else:
            parser = ap.ArgumentParser(description = 'Z_n STRUCTURE EMULATOR', epilog = 'Demonstrating calculations e.g. +, -, *, finding multiplicative inverse, and fast modular exponentiation!\n')
            parser.add_argument('n', action = 'store', type = int, help = 'Base n for Z_n structure')
            parser.add_argument('a', action = 'store', type = int, help = 'A number to calculate')
            parser.add_argument('b', action = 'store', type = int, help = 'And a second number')

            try:
                args = parser.parse_args()
            except:
                parser.print_help()
                return

            if not ZN_COND_N(args.n):
                print('ERROR: n must be >= 2! Exitting...')
            else:
                self.zn = Zn(args.n)
                self.a, self.b = self.zn.consider(args.a), self.zn.consider(args.b)
                self.exec(False)

    # A good website to compare result: https://defuse.ca/big-number-calculator.htm
    def exec(self, to_loop = True):
        a, b, zn = self.a, self.b, self.zn

        print('\n---- Considering {} ----\n'.format(zn))

        print('a = {}'.format(a))
        print('b = {}'.format(b))
        print()

        print('a + b = {}'.format(a + b))
        print('a - b = {}'.format(a - b))
        print('a * b = {}'.format(a * b))
        print()

        def mul_inv_proc(num : ZnNumber):
            res = num.mul_inv()
            if isinstance(res, ZnNumber):
                print('Multiplicative inverse of {}:'.format(num.original))
                print('--- using Bezout\'s Identity through extended Euclidean algorithm: {}'.format(res))
                print('--- using Euler\'s Theorem and fast modular exponentiation: {}'.format(num.mul_inv(mode = 'euler')))
            else:
                print(res)

        mul_inv_proc(a)
        mul_inv_proc(b)
        print()

        EXPANDER = 1024
        print('a ^ ({} * b) using fast modular exponentiation = {}'.format(EXPANDER, a ** (b.reduced * EXPANDER)))
        print('\n--------------------\n')

        if not to_loop:
            return

        while True:
            loop = input('Continue? [y/n] ').lower()
            if loop == 'y':
                return True
            elif loop == 'n':
                return False