Advertisement
kmahadev

Fraction

Dec 1st, 2012
17
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.10 KB | None | 0 0
  1. public class Fraction {
  2. private long num1,den1;
  3.  
  4. public Fraction(long num1, long den1) {
  5. this.num1 = num1;
  6. //check for divide by zero
  7. while (den1 == 0) {
  8. System.out.println("Denominator cannot be zero");
  9. //throw new IllegalArgumentException("Denominator is 0");
  10. System.out.println("Program is terminating");
  11. return;
  12. }
  13. this.den1 = den1;
  14.  
  15. }
  16.  
  17. public Fraction() {
  18. this.num1 = 0;
  19. this.den1 = 1;
  20. }
  21.  
  22. private boolean checkIfReduced(Fraction F){
  23. for(long i = 1; i <= F.getDen1(); i++){
  24. if(F.getDen1() % i == 0){
  25. return false;
  26. }
  27. }
  28. return true;
  29. }
  30.  
  31. private Fraction Reduce(Fraction F){
  32. //while not reduced
  33. while(checkIfReduced(F)){
  34. for(long i = 1; i <= F.getDen1(); i++){
  35. if(F.getDen1() % i == 0){
  36. F.setDen1(F.getDen1() / i);
  37. F.setNum1(F.getNum1() / i);
  38. }
  39. }
  40. }
  41. return F;
  42. }
  43.  
  44. public Fraction Add( Fraction f){ //899/391
  45. //long num11, den22;
  46. long num11 = f.num1, den11 = f.den1;
  47. num11 = ( (this.num1 * f.den1) + (f.num1 * this.den1) );
  48. den11 =(this.den1 * f.den1);
  49. return new Fraction(num11,den11);
  50. }
  51.  
  52. public Fraction subtract(Fraction f){
  53. long num11 = ( (this.getNum1() * f.getDen1()) - (f.getNum1() * this.getDen1()) );
  54. long den11 =(this.getDen1() * f.getDen1());
  55. return new Fraction(num11,den11);
  56. }
  57.  
  58. public Fraction multiply(Fraction f){
  59. long den11 =(this.getDen1() * f.getDen1());
  60. long num11 = (this.getNum1() * f.getNum1());
  61. return new Fraction(num11,den11);
  62. }
  63.  
  64. public Fraction divide(Fraction f){
  65.  
  66. long den11 = this.den1 * f.num1;
  67.  
  68. long num11 = this.num1 * f.den1;
  69. return new Fraction(num11,den11);
  70. }
  71.  
  72. public void setNum1(long num1) {
  73. this.num1 = num1;
  74. }
  75.  
  76. public void setDen1(long den1) {
  77. this.den1 = den1;
  78. }
  79.  
  80. public long getNum1() {
  81. return num1;
  82. }
  83.  
  84.  
  85. public long getDen1() {
  86. return den1;
  87. }
  88.  
  89. @Override
  90. public String toString(){
  91. Reduce(this);
  92.  
  93. double result = (double)this.getNum1() / this.getDen1();
  94. System.out.println("Result: " + result);
  95. return this.getNum1() + " / " + this.getDen1();
  96. }
  97. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement