Laran Evans
I develop software people love to use.
  • Home
  • About
  • Contact
  • Resume
  • Testimonials
Skip to content
  • Entrepreneurship
    • Leadership
    • Project Management
    • Team Development
    • Time Management
  • Puzzles
  • Software Architecture
    • Cloud Computing
  • Software Development
    • Algorithms
    • CSS
    • Java
    • Javascript
    • MySQL
    • PHP
    • Python
    • Ruby and Rails
    • System Administration
« Resolve MySQL Issues in Rails on Windows
Basic Bit Operations in Java »

Arithmetic from Addition

By laran | Published: 2010/01/14

The Challenge

Write methods to implement addition, subtraction and division using only addition.

The Solution

function multiply(x, y) {
  z = 0;
  for(i = 0; i < y; i++) {
    z +=x;
  }
  return z;
}

function negate(x) {
  y = 0;
  a = x < 0 ? 1 : -1;
  for(i = 0; i < x; i++) {
    y += a;
  }
  return y;
}

function subtract(x,fromY) {
  return fromY + negate(x);
}

function divide(x, byY) {
  r = 0;
  s = 0;
  while(s < x) {
    r += 1;
    s += byY;
  }
  return r;
}
This entry was posted in Algorithms and tagged interview questions. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.
« Resolve MySQL Issues in Rails on Windows
Basic Bit Operations in Java »

Post a Comment

Click here to cancel reply.

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

  • About Me

    I've got a masters degree in computer science and over 10 years of experience building web-based systems using Java/J2EE, Ruby, Rails and PHP. I'm a strong believer in the effectiveness of Agile Methods. Read more »

  • Subscribe

  • Table of Contents
    • The Challenge
    • The Solution
  • Similar Posts
    • All Files Recursively
    • Quicksort
    • AtoI
    • String Permutations
    • Binary Logic Basics
  • From Around the Web

    • Web App Business Models: User Needs and What People Pay For (Box UK Blog)
    • Blog Writing Tips from the World’s Most Famous Authors (Blogsessive.com)
    • How to get exponential success on your blog (CatsWhoBlog.com)
    • The Four Stages of Growing a Blog (Daily Blog Tips)
    • Insert Google Analytics without editing your theme (WpRecipes.com)
    Shared Items
  • Recent Posts

    • 80 pages of Ruby on Rails Performance Optimization Tips
    • Ruby Garbage Collection In-Depth
    • Binary Logic Basics
    • Kuali in Nacubo Magazine
    • Ruby Blocks, Procs, Lambda
  • Older Posts By Month

    Let's Talk

    Ask a question below. You'll be prompted for your name and email after you click the "Ask" button.

Know more. Accomplish more. Succeed.