Advertisement
Guest User

Untitled

a guest
Jun 17th, 2019
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.63 KB | None | 0 0
  1. package com.company;
  2.  
  3. public class Main {
  4. //Default function
  5. static final int NEGATIVE_ONE = -1;
  6. static final int ONE = 1;
  7.  
  8. static int add(int firstValue, int secondValue) {
  9. return firstValue + secondValue;
  10. }
  11.  
  12. static int negate(int a) {
  13. int c;
  14. int n = 0;
  15. if (a > 0) {
  16. c = NEGATIVE_ONE;
  17. } else {
  18. c = ONE;
  19. }
  20. while (a != 0) {
  21. a = add(a, c);
  22. n = add(n, c);
  23. }
  24. return n;
  25. }
  26. //////////////////////////////////////////////////////////////////////
  27. //Pseudocode is the comment of gist.
  28. static int minus(int firstVal, int secondVal) {
  29. return firstVal + negate(secondVal);
  30. }
  31.  
  32. static int multiply(int firstVal, int secondVal) {
  33. int answer = 0;
  34. for (int i = 0; i < secondVal; i++) {
  35. answer += firstVal;
  36. }
  37. return answer;
  38. }
  39.  
  40. static int divide(int firstVal, int secondVal) {
  41. if (secondVal == 0) {
  42. throw new ArithmeticException("Cannot divide by zero!");
  43. }
  44. int count = 0;
  45. int tmp = firstVal;
  46. while (tmp > 0) {
  47. tmp -= secondVal;
  48. count++;
  49. if (tmp == 0)
  50. break;
  51. if (tmp < 0) {
  52. System.out.println("error");
  53. return -1;
  54. }
  55. }
  56. return count;
  57. }
  58.  
  59. public static void main(String[] args) {
  60. System.out.println(minus(10, 5));
  61. System.out.println(multiply(7, 3));
  62. System.out.println(divide(14, 7));
  63. System.out.println(divide(15, 7)); //-1 to indicate error
  64. }
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement