Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.company;
- public class Main {
- //Default function
- static final int NEGATIVE_ONE = -1;
- static final int ONE = 1;
- static int add(int firstValue, int secondValue) {
- return firstValue + secondValue;
- }
- static int negate(int a) {
- int c;
- int n = 0;
- if (a > 0) {
- c = NEGATIVE_ONE;
- } else {
- c = ONE;
- }
- while (a != 0) {
- a = add(a, c);
- n = add(n, c);
- }
- return n;
- }
- //////////////////////////////////////////////////////////////////////
- //Pseudocode is the comment of gist.
- static int minus(int firstVal, int secondVal) {
- return firstVal + negate(secondVal);
- }
- static int multiply(int firstVal, int secondVal) {
- int answer = 0;
- for (int i = 0; i < secondVal; i++) {
- answer += firstVal;
- }
- return answer;
- }
- static int divide(int firstVal, int secondVal) {
- if (secondVal == 0) {
- throw new ArithmeticException("Cannot divide by zero!");
- }
- int count = 0;
- int tmp = firstVal;
- while (tmp > 0) {
- tmp -= secondVal;
- count++;
- if (tmp == 0)
- break;
- if (tmp < 0) {
- System.out.println("error");
- return -1;
- }
- }
- return count;
- }
- public static void main(String[] args) {
- System.out.println(minus(10, 5));
- System.out.println(multiply(7, 3));
- System.out.println(divide(14, 7));
- System.out.println(divide(15, 7)); //-1 to indicate error
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement