Is Prime (C#)

December 30, 2014 at 10:34 (.Net) ()

        static void Main(string[] args)
        {
            Console.Write("Enter a positive number: ");
            int num = int.Parse(Console.ReadLine());
            int divider = 2;
            int maxDivider = (int)Math.Sqrt(num);
            bool prime = true;
            
            while (prime && (divider <= maxDivider))
            {
                if (num % divider == 0)
                {
                    prime = false;
                }
                divider++;
            }

            Console.WriteLine("Prime? " + prime);
        }
Advertisements

Permalink Leave a Comment

Shifting number with position and value (C#)

December 30, 2014 at 10:17 (.Net) ()

        static void Main(string[] args)
        {
            /** Chapter 3 Example 13 (no user input) **/
            byte aByte = 35;
            int p = 2;
            int v = 1;

            if (v == 0)
            {
                Set(ref aByte, p, false);
            }
            else if (v == 1)
            {
                Set(ref aByte, p, true);
            }

            Console.WriteLine(aByte);
        }

        public static void Set(ref byte aByte, int pos, bool value)
        {
            if (value)
            {
                //left-shift 1, then bitwise OR
                aByte = (byte)(aByte | (1 << pos));
            }
            else
            {
                //left-shift 1, then take complement, then bitwise AND
                aByte = (byte)(aByte & ~(1 << pos));
            }
        }

        public static bool Get(byte aByte, int pos)
        {
            //left-shift 1, then bitwise AND, then check for non-zero
            return ((aByte & (1 << pos)) != 0);
        }

Permalink Leave a Comment