コード例 #1
0
 public void AddNatural(Natural unit)
 {
     unit.ID = naturals.Count;
     naturals.Add(unit.ID, unit);
     unit.transform.SetParent(NaturalGroup, false);
     unit.BindCells(true);
 }
        public void TestDeserialization()
        {
            Natural n = new Natural();

            n.FromWord("4");
            Assert.AreEqual(n.value, 4);
        }
コード例 #3
0
    public IEnumerator <Coroutine> LoadNatural(string path)
    {
        ClearNaturals();
        using (BinaryReader reader = new BinaryReader(File.OpenRead(Path.Combine(path, "natural.dat")))) {
            int header = reader.ReadInt32();
            if (header <= 0)
            {
                int counter = reader.ReadInt32();
                for (int i = 0; i < counter; i++)
                {
                    TriCoordinates coord  = TriCoordinates.Load(reader);
                    Natural        loaded = Natural.Load(reader);
                    if (loaded)
                    {
                        loaded.ID       = i;
                        loaded.Location = grid.GetCell(coord);
                        loaded.transform.SetParent(NaturalGroup);
                        AddNatural(loaded);
                        loaded.validateRotation();
                    }
//                    if (i % Strings.refreshLimit == 0) yield return null;
                }
            }
            else
            {
                Debug.LogWarning("Unknown naturals format " + header);
            }
        }
        yield return(null);
    }
コード例 #4
0
 public void DivRem(Natural dividend, Natural divisor)
 {
     Natural quotient, remainder;
     DivRem(dividend, divisor, out quotient, out remainder);
     dividend.SetValue(quotient);
     divisor.SetValue(remainder);
 }
コード例 #5
0
        public BindingList <Natural> listarClienteNatural()
        {
            BindingList <Natural> lista = new BindingList <Natural>();

            Conexion con = new Conexion();

            if (con.IsConnected())
            {
                MySqlCommand comando = new MySqlCommand();
                comando.CommandType = System.Data.CommandType.StoredProcedure;
                comando.CommandText = "LISTAR_CLIENTE_NATURAL";
                comando.Connection  = con.Connection;
                MySqlDataReader reader = comando.ExecuteReader();
                while (reader.Read())
                {
                    Natural n = new Natural();
                    n.ApMat     = reader.GetString("AP_MATERNO");
                    n.ApPat     = reader.GetString("AP_PATERNO");
                    n.Direccion = reader.GetString("DIRECCION");
                    n.Dni       = reader.GetString("DNI");
                    n.Email     = reader.GetString("EMAIL");
                    n.FechaNac  = (DateTime)reader.GetMySqlDateTime("FECHA_NACIMIENTO");
                    n.IdPersona = reader.GetInt32("ID_PERSONA").ToString();
                    n.Nombre    = reader.GetString("NOMBRE");
                    n.Sexo      = reader.GetChar("SEXO");
                    n.Telefono  = reader.GetString("TELEFONO");
                    lista.Add(n);
                }
                con.Close();
            }
            return(lista);
        }
コード例 #6
0
        public void DivisionTest()
        {
            Natural.DefaultNumberSize = defnumsize;

            foreach (ulong l in samples)
            {
                foreach (ulong r in samples)
                {
                    Natural ll = new Natural(l);
                    Natural rr = new Natural(r);

                    BigInteger bl = new BigInteger(l);
                    BigInteger br = new BigInteger(r);

                    if (r == 0)
                        continue;

                    BigInteger resb = bl / br;
                    BigInteger resn = (BigInteger)(ll / rr);

                    if (resb != resn)
                        Debugger.Break();

                    Assert.AreEqual(resb, resn);
                }
            }
        }
コード例 #7
0
        protected void btnEliminar_Click(object sender, EventArgs e)
        {
            try
            {
                Cliente clienteNatural = new Cliente(txtEliminar.Text);

                if (clienteNatural != null)
                {
                    Natural           personaNatural = new Natural(txtEliminar.Text);
                    Telefono          telefono       = new Telefono();
                    List <Telefono>   listaTelefono  = telefono.Leer(clienteNatural);
                    CorreoElectronico correo         = new CorreoElectronico(clienteNatural.CodigoCorreoElectronico);

                    foreach (Telefono numero in listaTelefono)
                    {
                        numero.Eliminar();
                    }
                    personaNatural.Eliminar();
                    clienteNatural.Eliminar();
                    correo.Eliminar();

                    ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('la persona ha sido eliminada');" +
                                                        "window.location ='Clientes_Admin.aspx';", true);
                }
                else
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('La persona no existe');", true);
                }
            }
            catch (Exception ex)
            {
                Session["mensajeError"] = "Ha ocurrido un error con la base de datos. " + ex;
                ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('No hay conexión con la base de datos');", true);
            }
        }
コード例 #8
0
        public int registrarClienteNatural(Natural c)
        {
            Conexion con = new Conexion();

            if (con.IsConnected())
            {
                MySqlCommand comando = new MySqlCommand();
                comando.CommandType = System.Data.CommandType.StoredProcedure;
                comando.CommandText = "REGISTRAR_CLIENTE_NATURAL";
                comando.Connection  = con.Connection;
                comando.Parameters.Add("_NOMBRE", MySqlDbType.VarChar).Value     = c.Nombre;
                comando.Parameters.Add("_DNI", MySqlDbType.VarChar).Value        = c.Dni;
                comando.Parameters.Add("_AP_PATERNO", MySqlDbType.VarChar).Value = c.ApPat;
                comando.Parameters.Add("_AP_MATERNO", MySqlDbType.VarChar).Value = c.ApMat;
                comando.Parameters.Add("_SEXO", MySqlDbType.VarChar).Value       = c.Sexo;
                comando.Parameters.Add("_FECHA_NAC", MySqlDbType.Date).Value     = c.FechaNac;
                comando.Parameters.Add("_TELEFONO", MySqlDbType.VarChar).Value   = c.Telefono;
                comando.Parameters.Add("_EMAIL", MySqlDbType.VarChar).Value      = c.Email;
                comando.Parameters.Add("_DIRECCION", MySqlDbType.VarChar).Value  = c.Direccion;

                comando.Parameters.Add("_ID_PERSONA", MySqlDbType.Int32).Direction = System.Data.ParameterDirection.Output;

                int check = comando.ExecuteNonQuery();
                con.Close();
                if (check == 1)
                {
                    return(Int32.Parse(comando.Parameters["_ID_PERSONA"].Value.ToString()));
                }
                else
                {
                    return(0);
                }
            }
            return(-1);
        }
コード例 #9
0
ファイル: DefaultAdder.cs プロジェクト: MrAksel/Massive
        public void Add(Natural x, Natural y)
        {
            int length = Math.Max(x.usedDigits, y.usedDigits);

            x.PushLength(length + 1);
            y.PushLength(length); // Expand so we know we can index those digits

            Digit carry = 0;
            for (int i = 0; i < length; i++)
            {
                Carry res = (Carry)x.digits[i] + y.digits[i] + carry;
                Digit val;
                if (res > Digit.MaxValue)
                {
                    carry = 1;
                    val = (Digit)(res - Digit.MaxValue - 1);
                }
                else
                {
                    carry = 0;
                    val = (Digit)res;
                }

                x.digits[i] = val;
            }
            x.digits[length] = carry;
            x.usedDigits = length + (int)carry; // If carry == 1 we used another extra digit

            x.PopLength();
            y.PopLength();
        }
コード例 #10
0
        public void TestAddition()
        {
            Natural n1 = new Natural(1),
                    n2 = new Natural(2);

            Assert.AreEqual(new NaturalSemiring().Add(n1, n2).value, 3);
        }
コード例 #11
0
        public void AddTest()
        {
            Natural.DefaultNumberSize = defnumsize;

            foreach (ulong l in samples)
            {
                foreach (ulong r in samples)
                {
                    Natural ll = new Natural(l);
                    Natural rr = new Natural(r);

                    BigInteger bl = new BigInteger(l);
                    BigInteger br = new BigInteger(r);

                    Assert.AreEqual(bl + br, (BigInteger)(ll + rr));
                }
            }

            for (int i = 2; i < 10; i++)
            {
                for (int p = 32; p < 256; p += 12)
                {
                    BigInteger b = BigInteger.Pow(i, p);
                    BigInteger l = BigInteger.Pow(i + 1, p - 1) * 7;

                    BigInteger r = b + l;
                    Natural n = (Natural)b + (Natural)l;

                    Assert.AreEqual(r, (BigInteger)n);
                }
            }
        }
コード例 #12
0
ファイル: Natural.cs プロジェクト: dan10097110/D-CSharp-Lib
            //1,3
            public static bool Test(ulong exponent, ref ulong startI, ref Natural startS, List <ulong> primes)
            {
                if (!DLib.Math.Prime.Test.Probabilistic.Division(exponent, primes, 3, (ulong)System.Math.Sqrt(exponent) + 1))
                {
                    return(false);
                }
                lock (primes)
                {
                    int i = primes.Count;
                    for (; i > 0 && primes[i - 1] > exponent; i--)
                    {
                        ;
                    }
                    if (i > 0 && primes[i - 1] != exponent)
                    {
                        primes.Insert(i, exponent);
                    }
                }
                if ((exponent & 3) == 3 && DLib.Math.Prime.Test.Probabilistic.Division((exponent << 1) + 1, primes, 3, (ulong)System.Math.Sqrt((exponent << 1) + 1) + 1))
                {
                    return(false);
                }
                Natural mersenneNumber = MersenneNumber((int)exponent);

                return(TrialDivision(exponent, mersenneNumber, primes) && LucasLehmerTest(exponent, mersenneNumber, ref startI, ref startS));
            }
コード例 #13
0
ファイル: LongMultiplier.cs プロジェクト: MrAksel/Massive
        public void Multiply(Natural factor1, Natural factor2)
        {
            if (factor1 == 0 || factor2 == 0)
            {
                factor1.SetValue(Natural.Zero);
            }
            else if (factor2 == 1)
            {
                // factor1 = factor1    (jupp, that's the only optimization)
            }
            else
            {
                Natural product = Natural.Zero;

                for (int i = 0; i < factor1.usedDigits; i++)
                {
                    Digit d = factor1.digits[i];

                    Natural partial = MulDigit(factor2, d);
                    Natural.ShiftLeft(partial, i);

                    Natural.Add(product, partial);
                }

                factor1.SetValue(product);
            }
        }
コード例 #14
0
        public List <Natural> AutocompleteCliente()
        {
            List <Natural> Listado = null;
            Natural        Entidad = null;
            SqlDataReader  lector;

            conexion.Open();

            string query = "SELECT CONCAT(nComercial,' - ',ruc) autocomplete FROM Cli_Juridico ";

            query += "UNION ";
            query += "SELECT CONCAT(nombre,' ',apepat,' ',apemat,' - ',dni) autocomplete FROM Cli_Natural ";

            SqlCommand comando_val = new SqlCommand(query, conexion);

            lector = comando_val.ExecuteReader();

            if (lector.HasRows)
            {
                Listado = new List <Natural>();
                while (lector.Read())
                {
                    Entidad = new Natural();
                    Entidad.autocomplete = lector["autocomplete"].ToString();
                    Listado.Add(Entidad);
                }
            }
            conexion.Close();

            return(Listado);
        }
コード例 #15
0
        public void Multiply(Natural factor1, Natural factor2)
        {
            if (factor1 == Natural.Zero || factor2 == Natural.Zero)
            {
                factor1.SetValue(Natural.Zero);
            }
            else if (factor1 == Natural.One)
            {
                factor1.SetValue(factor2);
            }
            else
            {
                Natural increase = factor1.Clone();
                Natural decrease = factor2.Clone();

                factor1.PushLength(factor1.usedDigits * factor2.usedDigits);

                while (decrease > 1) // We already have 1 factor1
                {
                    Natural.Add(factor1, increase);
                    Natural.Decrement(decrease);
                }

                factor1.PopLength();
            }
        }
コード例 #16
0
        public void TestMultiplication()
        {
            Natural n1 = new Natural(2),
                    n2 = new Natural(3);

            Assert.AreEqual(new NaturalSemiring().Multiply(n1, n2).value, 6);
        }
コード例 #17
0
        public List <Natural> ListarEstado()
        {
            List <Natural> Listado = null;
            Natural        Entidad = null;
            SqlDataReader  lector;

            //Abrimos conexión
            conexion.Open();

            //Creamos un sqlCommand junto con el query para poder consultar a la bd.
            string query = "SELECT id_estado, estado FROM Estados";

            SqlCommand comando_val = new SqlCommand(query, conexion);

            lector = comando_val.ExecuteReader();

            if (lector.HasRows)
            {
                Listado = new List <Natural>();
                while (lector.Read())
                {
                    Entidad                    = new Natural();
                    Entidad.id_estado          = int.Parse(lector["id_estado"].ToString());
                    Entidad.estado_descripcion = lector["estado"].ToString();
                    Listado.Add(Entidad);
                }
            }
            //Despues, cerramos la conexion!
            conexion.Close();

            //Retorna el listao lleno de datos
            return(Listado);
        }
コード例 #18
0
        public void Subtract(Natural minuend, Natural subtrahend)
        {
            /*
             * If y is zero, return x
             * If x is larger than y, use Sub1
             * If x is smaller than y, would return negative
             * If x == y, set x to 0 and return x
             */

            if (subtrahend == 0)
            {
            }
            else if (minuend > subtrahend)
            {
                int digits = minuend.usedDigits;
                Natural.Complement(Natural.Add(Natural.Complement(minuend), subtrahend), digits);
            }
            else if (minuend < subtrahend)
            {
                throw new InvalidOperationException(Resources.Strings.WouldBeNegative);
            }
            else
            {
                minuend.Clear();
            }
        }
コード例 #19
0
ファイル: Rational.cs プロジェクト: dan10097110/D-CSharp-Lib
        void Shorten()
        {
            Natural gcd = Natural.GCD(Denominator, (Natural)Numerator);

            Numerator   /= gcd;
            Denominator /= gcd;
        }
コード例 #20
0
ファイル: CarrySubtracter.cs プロジェクト: MrAksel/Massive
 public void Subtract(Natural minuend, Natural subtrahend, out Natural difference)
 {
     int cmp = minuend.CompareTo(subtrahend);
     if (cmp < 0)
     {
         throw new InvalidOperationException(Resources.Strings.WouldBeNegative);
     }
     else if( cmp == 0)
     {
         difference = Natural.Zero;
     }
     else
     {
         IndexedArraySegment<Digit> digits = new Digit[minuend.usedDigits];
         int carry = 0;
         int msd = 0;
         for (int i = 0; i < minuend.usedDigits; i++)
         {
             long diff = (long)minuend.digits[i] - subtrahend.digits[i] - carry;
             if (diff < 0) // Need to borrow from next
             {
                 diff = diff + Digit.MaxValue + 1;
                 carry = 1;
                 digits[i] = (Digit)diff;
             }
             else if (diff > 0)
             {
                 digits[i] = (Digit)diff;
                 carry = 0;
                 msd = i;
             }
         }
         difference = new Natural(digits, msd + 1);
     }
 }
コード例 #21
0
        public void NumberTheory_Basic_Test()
        {
            var     natural = new Natural(9);
            var     relative_natural = new Natural(38);
            var     valid_natural = new Natural(36);
            int     relativelyprime = 1, gcd = 9, lcm = 342;
            Natural actual;

            actual = natural.Gcd(relative_natural);
            //actual = relative_natural.Gcd(natural);
            Assert.AreEqual(relativelyprime, actual.GetIntValue());
            Console.WriteLine("Relatively Prime (38,9): " + actual.GetIntValue());

            natural = new Natural(9);
            var IsRelativelyPrime = natural.IsRelativelyPrimeTo(relative_natural);

            Assert.AreEqual(true, IsRelativelyPrime);
            Console.WriteLine("Relatively Prime (38,9): " + IsRelativelyPrime);

            natural = new Natural(0);
            var IsPrime = natural.IsPrime();

            Console.WriteLine("Is 38 Prime?: " + IsPrime);

            natural = new Natural(9);
            actual  = natural.Lcm(relative_natural);
            Assert.AreEqual(lcm, actual.GetIntValue());
            Console.WriteLine("Valid LCM (38,9): " + actual.GetIntValue());

            natural = new Natural(9);
            actual  = natural.Gcd(valid_natural);
            Assert.AreEqual(gcd, actual.GetIntValue());
            Console.WriteLine("Valid GCD (36,9): " + actual.GetIntValue());
        }
コード例 #22
0
        public void Multiply(Natural factor1, Natural factor2, out Natural product)
        {
            if (factor1 == Natural.Zero || factor2 == Natural.Zero)
            {
                product = Natural.Zero;
            }
            else if (factor1 == Natural.One)
            {
                product = factor2.Clone();
            }
            else
            {
                Natural counter = factor2.Clone();
                product = factor1.Clone();

                product.PushLength(factor1.usedDigits * factor2.usedDigits);

                while (counter > 1) // We already have 1 factor1
                {
                    Natural.Add(product, factor1);
                    Natural.Decrement(counter);
                }

                product.PopLength();
            }
        }
コード例 #23
0
    public void RemoveNatural(int id)
    {
        Natural unit = naturals[id];

        Destroy(unit.gameObject);
        naturals.Remove(id);
    }
コード例 #24
0
ファイル: LongMultiplier.cs プロジェクト: MrAksel/Massive
        public void Multiply(Natural factor1, Natural factor2, out Natural product)
        {
            if (factor1 == 0 || factor2 == 0)
            {
                product = Natural.Zero;
            }
            else if (factor2 == 1)
            {
                product = factor1.Clone();
            }
            else
            {
                product = Natural.Zero;

                for (int i = 0; i < factor1.usedDigits; i++)
                {
                    Digit d = factor1.digits[i];

                    Natural partial = MulDigit(factor2, d);
                    Natural.ShiftLeft(partial, i);

                    Natural.Add(product, partial);
                }
            }
        }
コード例 #25
0
    static void Main()
    {
        var e1 = Natural.Create(100);
        int n;

        e1.Increment();
        e1.GetNumber(out n);
    }
コード例 #26
0
 public AI(Character IAM)
 {
     intensity       = Ferocity.Balanced;
     perferredTarget = Target.Any;
     state           = Natural.Balanced;
     intelligence    = Intelligence.Normal;
     owner           = IAM;
 }
コード例 #27
0
ファイル: Integer.cs プロジェクト: MrAksel/Massive
        public Integer(Natural x)
        {
            sign = 0;
            magnitude = x;

            if (magnitude > 0)
                sign = 1;
        }
コード例 #28
0
ファイル: Conversion.cs プロジェクト: Amichai/OOMath
        public static Natural ToNatural(this long num)
        {
            if (num < 0) throw new ArgumentOutOfRangeException("num");

            var retVal = Natural.Zero;
            for (long i = 0; i < num; i++)
                retVal = new Natural(retVal);
            return retVal;
        }
コード例 #29
0
        protected void btnGuardarCambios(object sender, EventArgs e)
        {
            try
            {
                int   CodLug1 = this.CodLugar(dplParroquia, dplMunicipio, dplEstado);
                Lugar lugar   = new Lugar(CodLug1);

                Natural ClienteNatural = new Natural(dplRif.SelectedValue + txtRif.Text);


                CorreoElectronico ctrlCorreo = new CorreoElectronico(ClienteNatural.CodigoCorreoElectronico);
                ctrlCorreo.Direccion = txtCorreo.Text;
                ctrlCorreo.Actualizar();

                //Cliente datosCliente = new Cliente(dplRif.SelectedValue + txtRif.Text, txtContraseña.Text, ctrlCorreo, null);
                //datosCliente.Actualizar();

                ClienteNatural.Password  = txtContraseña.Text;
                ClienteNatural.Cedula    = dplCedula.SelectedValue + txtCedula.Text;
                ClienteNatural.Nombre1   = Nombre1.Text;
                ClienteNatural.Nombre2   = Nombre2.Text;
                ClienteNatural.Apellido1 = Apellido1.Text;
                ClienteNatural.Apellido2 = Apellido2.Text;
                ClienteNatural.Direccion = lugar.Codigo;

                //Natural natural = new Natural(dplRif.SelectedValue + txtRif.Text, txtContraseña.Text,ctrlCorreo, dplCedula.SelectedValue + txtCedula.Text,Nombre1.Text,Nombre2.Text,Apellido1.Text,Apellido2.Text,lugar);
                ClienteNatural.Actualizar();

                Telefono        telefono  = new Telefono();
                List <Telefono> telefonos = telefono.Leer(ClienteNatural);


                Telefono telefono1 = new Telefono(int.Parse(CodigoPais1.SelectedValue), int.Parse(CodAre.Text), int.Parse(txtTelefono1.Text), TipoTelf.Text, ClienteNatural);
                Telefono telefono2 = new Telefono(int.Parse(CodigoPais2.SelectedValue), int.Parse(CodAre2.Text), int.Parse(txtTelefono2.Text), TipoTelf2.Text, ClienteNatural);

                if (!VerificarCambiosTelefono(telefonos[0], telefono1))
                {
                    telefonos[0].Eliminar();
                    telefono1.Insertar();
                }

                if (!VerificarCambiosTelefono(telefonos[1], telefono2))
                {
                    telefonos[1].Eliminar();
                    telefono2.Insertar();
                }

                //Response.Redirect("/Views/Clientes_Admin.aspx", false);
                ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('El cliente se ha sido modificado exitosamente');" +
                                                    "window.location ='Clientes_Admin';", true);
            }
            catch (Exception ex)
            {
                Session["mensajeError"] = "Ha ocurrido un error al modificar el cliente natural. " + ex;
                ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('NO DEBE HABER CAMPOS VACÍOS');", true);
            }
        }
コード例 #30
0
        public static void Integers()
        {
            Natural n1 = 5;
            Integer n2 = -10;

            Integer itg = n1 - (int)n2;

            Console.WriteLine(itg);
        }
コード例 #31
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="a"></param>
        /// <param name="b"></param>
        /// <returns>a < b: - 1; a == b: 0; a > b: == 1</b></returns>
        public static int Compare(Integer a, Integer b)
        {
            int i = Natural.Compare(a.Abs(), b.Abs());

            if (i == 0 && a.IsZero())
            {
                return(0);
            }
            return((a.Positive ? 1 : -1) * (a.Positive != b.Positive ? 1 : i));
        }
コード例 #32
0
        public static Integer Parse(string value, bool positive = true, bool hex = false)
        {
            if (!hex && !Regex.IsMatch(value, @"^-?[0-9]+$") ||
                hex && !Regex.IsMatch(value, @"^-?[0-9a-fA-F]+$"))
            {
                throw new ArgumentException($"String was not in correct format: {value}.");
            }

            return(value.StartsWith("-") ? new Integer(Natural.Parse(value.Substring(1)), false) : new Integer(Natural.Parse(value), positive));
        }
コード例 #33
0
        public Integer(string value, bool hex = true)
        {
            if (value.StartsWith("-"))
            {
                Positive = false;
                value    = value.Substring(1);
            }

            Absolute = new Natural(value, hex);
        }
コード例 #34
0
        public static Integer Pow(Integer b, Natural exp)
        {
            Integer result = 1;

            for (Integer i = 0; i < exp; i++)
            {
                result *= b;
            }

            return(result);
        }
コード例 #35
0
 /// <summary>
 /// Выбор минимального значения
 /// </summary>
 static Natural Min(Natural N1, Natural N2)
 {
     if (N_1.Run(N1, N2) == 2)
     {
         return(N1);
     }
     else
     {
         return(N2);
     }
 }
コード例 #36
0
        public void Addition_Test()
        {
            var  natural1 = new Natural(Int32.MaxValue);
            var  natural2 = new Natural(Int64.MaxValue);
            bool expected = true;
            var  actual   = natural1.Add(natural2);

            Assert.AreEqual(expected, (actual.GetBigValue() > Int64.MaxValue));

            Console.WriteLine("The Big Integer sum is: " + actual.GetBigValue());
        }
コード例 #37
0
        static void Main(string[] args)
        {
            Func <int, int> sqr = capturedVar => capturedVar * capturedVar;

            // Single-treaded for loop is easy
            for (int i = 1; i <= 5; i++)
            {
                int outerVar = i;                 // struct/ValueType make a copy on assignment. delegate/lambda may change it!
                Console.WriteLine(sqr(outerVar)); // outerVar is a captured variable, lambda expression sqr is a closure
            }

            Action[] actions = new Action[3];
            for (int i = 0; i < actions.Length; i++)
            {
                // each closure catches the same 'i' variable
                actions[i] = () => Console.Write(i);
            }
            foreach (var action in actions)
            {
                action();                             // 333
            }
            Console.WriteLine();

            for (int i = 0; i < actions.Length; i++)
            {
                int localScopedVar = i;
                // each closure captures a fresh localScopedVar
                actions[i] = () => Console.Write(localScopedVar);
            }
            foreach (var action in actions)
            {
                action();                             // 012
            }
            Console.WriteLine();

            for (int i = 0; i < 3; i++)
            {
                var f = Natural();
                Console.WriteLine($"{f()} \t{Natural()()}");
            }
        }
コード例 #38
0
        public void Division_Algorithm_Test()
        {
            var natural  = new Natural(158);
            var natural2 = new Natural(17);
            var actual   = natural.DivisionAlgorithm(natural2);

            Console.WriteLine("The Division Algorithm of {0} / {1} is: " + actual, natural, natural2);
            natural  = new Natural(int.MaxValue);
            natural2 = new Natural(86340);
            actual   = natural.DivisionAlgorithm(natural2);
            Console.WriteLine("The Division Algorithm of {0} / {1} is: " + actual, natural, natural2);
        }
コード例 #39
0
 public void Domain_Exception_Test()
 {
     try
     {
         var negative_natural = new Natural(-5);
     }
     catch (ArgumentException e)
     {
         Console.WriteLine(e);
         throw;
     }
 }
コード例 #40
0
 public bool RegistrarCliente(Natural cli)
 {
     //AQUI ELK PROFE APLICO LA MANIPULACION DE TRY CATCH!, APLICAR A TODO DE LA CAP NEGOCIO
     try
     {
         var aux = clienteDatos.RegistrarCliente(cli);
         return(true);
     }
     catch (Exception)
     {
         return(false);
     }
 }
コード例 #41
0
        public void Prime_Test()
        {
            var val      = new Natural(199);
            var exponent = new Natural(7);
            var modulo   = new Natural(3);
            var expected = true;

            var actual = val.IsPrime();

            Assert.AreEqual(expected, actual);

            Console.WriteLine("The value of expected {0} vs actual: " + actual, expected);
        }
コード例 #42
0
        public void Mod_Test()
        {
            var val      = new Natural(52);
            var exponent = new Natural(7);
            var modulo   = new Natural(3);
            var expected = BigInteger.ModPow(52, 7, 3);

            var actual = val.ModPow(exponent, modulo);

            Assert.AreEqual(expected, actual.GetBigValue());

            Console.WriteLine("The value of expected {0} vs actual: " + actual.GetBigValue(), expected);
        }
コード例 #43
0
ファイル: LongMultiplier.cs プロジェクト: MrAksel/Massive
        private static Natural MulDigit(Natural x, Digit y)
        {
            Natural total = 0;
            for (int i = 0; i < x.usedDigits; i++)
            {
                Natural partial = (Carry)x.digits[i] * y;
                Natural.ShiftLeft(partial, i);

                Natural.Add(total, partial);
            }

            return total;
        }
コード例 #44
0
        public void DivRem(Natural dividend, Natural divisor, out Natural quotient, out Natural remainder)
        {
            if (divisor == 0)
                throw new DivideByZeroException();

            dividend = dividend.Clone();

            quotient = 0;

            while (dividend >= divisor)
            {
                Natural.Subtract(dividend, divisor);
                Natural.Increment(quotient);
            }

            remainder = dividend;
        }
コード例 #45
0
ファイル: RecursiveDivider.cs プロジェクト: MrAksel/Massive
        private void InternalDivRem(Natural dividend, Natural divisor, out Natural quotient, out Natural remainder)
        {
            int dcmp = dividend.CompareTo(divisor);
            if (dcmp == 0)
            {
                quotient = Natural.One;
                remainder = Natural.Zero;
            }
            else if (dcmp < 0) // dividend < divisor
            {
                quotient = Natural.Zero;
                remainder = dividend.Clone(); // Do we have to clone?
            }
            else // dividend > divisor
            {
                Natural modifiedDivisor = divisor.Clone();
                Natural subquotient = Natural.One;

                long bitshifts = Natural.Log2(dividend) - Natural.Log2(modifiedDivisor); // Gets how many factors of two from divisor to dividend
                Natural.BitShiftLeft(modifiedDivisor, bitshifts); // Shifts divisor that many times (multiply by 2^bitshifts)
                Natural.BitShiftLeft(subquotient, bitshifts);

                int cmp = dividend.CompareTo(modifiedDivisor);
                if (cmp < 0) // Dividend < modifiedDivisors - shifted 1 too much
                {
                    Natural.BitShiftRight(subquotient, 1); // Divide by 2 to get the right quotient
                    Natural.BitShiftRight(modifiedDivisor, 1);
                }
                else if (cmp == 0) // Divisor equal to dividend!
                {
                    quotient = subquotient;
                    remainder = Natural.Zero;
                    return;
                }

                // dividend > modifiedDivisor
                Natural newDividend = Natural.Subtract(dividend, modifiedDivisor); // Optimize away the clone (put this in private function - clone up front)
                InternalDivRem(newDividend, divisor, out quotient, out remainder); // Repeat division on difference between dividend and modifiedDivisor

                Natural.Add(quotient, subquotient); // Add the quotient we calculated in this iteration
            }
        }
コード例 #46
0
ファイル: NaturalTests.cs プロジェクト: MrAksel/Massive
        public void DivisionTest()
        {
            Natural.DefaultNumberSize = 4;

            foreach (ulong l in samples)
            {
                foreach (ulong r in samples)
                {
                    Natural ll = new Natural(l);
                    Natural rr = new Natural(r);

                    BigInteger bl = new BigInteger(l);
                    BigInteger br = new BigInteger(r);

                    if (r == 0)
                        continue;

                    Assert.AreEqual(bl / br, (BigInteger)(ll / rr));
                }
            }
        }
コード例 #47
0
ファイル: DefaultAdder.cs プロジェクト: MrAksel/Massive
 public void Add(Natural addend1, Natural addend2, out Natural sum)
 {
     sum = addend1.Clone();
     Add(sum, addend2);
 }
コード例 #48
0
 public INaturalMultiplier GetMultiplier(Natural n1, Natural n2)
 {
     return GetDefaultMultiplier();
 }
コード例 #49
0
ファイル: CarrySubtracter.cs プロジェクト: MrAksel/Massive
 public void Subtract(Natural minuend, Natural subtrahend)
 {
     Natural difference;
     Subtract(minuend, subtrahend, out difference);
     minuend.SetValue(difference);
 }
コード例 #50
0
 public INaturalSubtracter GetSubtracter(Natural n1, Natural n2)
 {
     return GetDefaultSubtracter();
 }
コード例 #51
0
        public void MultiplyTest()
        {
            Natural.DefaultNumberSize = defnumsize;

            foreach (ulong l in samples)
            {
                foreach (ulong r in samples)
                {
                    Natural ll = new Natural(l);
                    Natural rr = new Natural(r);

                    BigInteger bl = new BigInteger(l);
                    BigInteger br = new BigInteger(r);

                    BigInteger bres = bl * br;
                    BigInteger nres = (BigInteger)(ll * rr);

                    Debug.WriteLine("{0:X} * {1:X} = {2:X} = {3:X}", l, r, bres, nres);

                    Assert.AreEqual(bres, nres);
                }
            }

            Natural pow = 1;
            BigInteger bi = BigInteger.Pow(2147483647, 5);
            pow *= 2147483647;
            pow *= 2147483647;
            pow *= 2147483647;
            pow *= 2147483647;
            pow *= 2147483647;
            if (bi != (BigInteger)pow)
                Assert.Fail("Pow. Got {0}, should be {1}", (BigInteger)pow, bi);
        }
コード例 #52
0
 public void Subtract(Natural minuend, Natural subtrahend, out Natural difference)
 {
     difference = minuend.Clone();
     Subtract(difference, subtrahend);
 }
コード例 #53
0
        public void LargeNumTest()
        {
            Natural.DefaultNumberSize = defnumsize;

            int[] powers = { 0, 1, 2, 3, 4, 5 };
            foreach (ulong l in samples)
            {
                foreach (int p in powers)
                {
                    Natural ll = new Natural(l);
                    BigInteger bl = new BigInteger(l);

                    BigInteger rs = (BigInteger)Natural.Pow(ll, p);
                    Assert.AreEqual(BigInteger.Pow(bl, p), rs);
                }
            }
        }
コード例 #54
0
ファイル: RecursiveDivider.cs プロジェクト: MrAksel/Massive
 public void DivRem(Natural dividend, Natural divisor, out Natural quotient, out Natural remainder)
 {
     InternalDivRem(dividend.Clone(), divisor, out quotient, out remainder);
 }
コード例 #55
0
        public void SubtractTest()
        {
            Natural.DefaultNumberSize = defnumsize;

            foreach (ulong l in samples)
            {
                foreach (ulong r in samples)
                {
                    if (r > l)
                        continue;

                    Natural ll = new Natural(l);
                    Natural rr = new Natural(r);

                    BigInteger bl = new BigInteger(l);
                    BigInteger br = new BigInteger(r);

                    Assert.AreEqual(bl - br, (BigInteger)(ll - rr));
                }
            }
        }
コード例 #56
0
 public void Remainder(Natural dividend, Natural divisor, out Natural remainder)
 {
     Natural quotient;
     DivRem(dividend, divisor, out quotient, out remainder);
 }
コード例 #57
0
ファイル: Integer.cs プロジェクト: MrAksel/Massive
 public Integer()
 {
     sign = 0;
     magnitude = 0;
 }
コード例 #58
0
 public INaturalDivider GetDivider(Natural n1, Natural n2)
 {
     return GetDefaultDivider();
 }
コード例 #59
0
 public INaturalAdder GetAdder(Natural n1, Natural n2)
 {
     return GetDefaultAdder();
 }
コード例 #60
0
        public void ToStringTest()
        {
            Natural.DefaultNumberSize = defnumsize;

            foreach (ulong l in samples)
            {
                Natural n = new Natural(l);
                BigInteger b = new BigInteger(l);

                string s = n.ToString();

                Assert.AreEqual(BigInteger.Parse(s), b);
            }
        }