Write methods to implement addition, subtraction and division using only addition.
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; }
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>
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>
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 »
Arithmetic from Addition
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; }