Grasshopper

algorithmic modeling for Rhino

what's the most direct way to verify if an integer is even or odd?

unless it somehow slipped by me, a component that verifies this and outputs a boolean value would be handy... but until then, which do you think is the least time consuming way to check if an integer is odd or even?

thanks!

Views: 2913

Replies to This Discussion

calculate the modulus (%) with Divisor 2. See if result is larger than 0. If so, A was odd, if not,  it was even.

yeah ,a friend actually told me that just now. the fun thing is there is no need to compare the result, since it's either way 0 or 1, so you can use the output values directly from the modulus component, which is cool (and which is probably why there isn't a component that verifies even/odd numbers.. :)) )

Thanks for your answer!

just know your math and the shortcuts of programming ;)

It's funny isn't it? Computers divide by 2 and humans look whether the last digit is 0, 2, 4, 6 or 8. Another prime example of why it is so difficult to teach programming sometimes.

--

David Rutten

david@mcneel.com

Seattle, WA

In assembler times, when division took like 20 times longer than loading a number into the CPU, there used to be a way to load only the very last bit and interpret that as a boolean.

Instant even/odd

It probably still takes 20 times longer today...

--

David Rutten

david@mcneel.com

Seattle, WA

Maybe this could do the trick:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int i = 0; i < 25; i++)
            {
                System.Collections.BitArray BA = new System.Collections.BitArray(new int[] { i });
                bool[] BITS= new bool[BA.Count];
                BA.CopyTo(BITS, 0);
                Console.WriteLine(BITS[0]);
            }
            Console.ReadLine();
        }
    }

cheers Michael

Would love to see that compiled vs. the Modulus version...  

RSS

About

Translate

Search

Photos

  • Add Photos
  • View All

Videos

  • Add Videos
  • View All

© 2024   Created by Scott Davidson.   Powered by

Badges  |  Report an Issue  |  Terms of Service