Problem of the Day
A new programming or logic puzzle every Mon-Fri

Seven Multiplication

Happy Monday! Hopefully not too many people are on vacation this week.

Today's problem is an easy one but may prove interesting. Without using the multiplication operator, how can you multiply an integer by 7?

Permalink: http://problemotd.com/problem/seven-multiplication/

Comments:

  • Anonymous - 10 years, 1 month ago

    C# extension method for N * M.

    public static int Multiply(this int i, int factor)
        {
            int pseudoProduct = 0;
    
            for (int j = 0; j < factor; j++)
            {
                pseudoProduct += i;
            }
    
            return pseudoProduct;
        }
    

    reply permalink

  • xTibor - 10 years, 1 month ago

    With shifting and addition in C/C++: int mul7(int a) { return (((a<<1)+a)<<1)+a; }

    reply permalink

  • David - 10 years ago

    Why not use subtraction? int mul7(int a) { return (a<<3)-a; }

    reply permalink

  • Driphter - 10 years, 1 month ago

    Clojure!

    ; Duh :P
    (defn mult-by-7 [x]
      (+ x x x x x x x))
    
    ; Okay for reals...
    (defn mult
      ([] 1)
      ([x] x)
      ([x y]
        (cond 
          (or (zero? x) (zero? y)) 0
          (pos? x) (apply + (repeat x y))
          (pos? y) (apply + (repeat y x))
          :else    (apply + (repeat (- x) (- y)))))
      ([x y & xs]
        (if (or (zero? x) (zero? y) (some zero? xs))
          0
          (reduce mult (mult x y) xs))))
    

    reply permalink

Content curated by @MaxBurstein