如何创建一个新的分数,如果一个分数不能被简化?

huangapple go评论74阅读模式
英文:

How would I make a new fraction if a fraction cannot be simplified?

问题

代码:

import java.util.Random;

class SimpleFracBoxes{

    private int numberOfFractions = 0;
    private String result = "";
    Random myRandom = new Random( );
    int min = 1;
    int max = 100000;

    public SimpleFracBoxes( )
    {
    }

    public SimpleFracBoxes(int nOFracs)
    {
        numberOfFractions = nOFracs;
    }

    public void makeTheFractions()
    {
        for (int i = 0; i < numberOfFractions; i++)
        {
            Fraction frac = getAGoodFraction();
            Fraction frac2 = frac.simplify();
            result = result + " " + (int)(i + 1) + ": " + frac + " simplifies to "+ frac2 + "\n" ;         
        }
    }

    private Fraction getAGoodFraction()
    {  
        Fraction frac;
        do {                      
            frac = new Fraction (myRandom.nextInt(max-min), myRandom.nextInt(max-min));      
        }      
        while (frac.getNumerator() >= frac.getDenominator());
        int num = frac.getNumerator();
        int denom = frac.getDenominator();
        int gcd = frac.gcd(num, denom);        
        if (gcd == 1)  {                  
            getAGoodFraction();                            
        } else if (gcd !=1) {                    
            frac.simplify();
        }              
        return frac;    
    }
    
    public String getFractions()
    {
        return result;
    }
}

public class Fraction{

    private int numerator;
    private int denominator;

    public Fraction(){
        this(0,1);
    }

    public Fraction(int number) {
        this(number,1);
    }

    public Fraction(Fraction frac) {
        this(frac.getNumerator(), frac.getDenominator());
    }
    
    public Fraction(int num, int denom){
        setNumerator(num);
        setDenominator(denom);
    }

    public static int gcd(int m, int n) {
        int r = n % m;
        while (r != 0) {
            n = m;
            m = r;
            r = n % m;
        }
        return m;
    }

    public static Fraction min(Fraction f1, Fraction f2) {
        double f1_dec = f1.decimal();
        double f2_dec = f2.decimal();
        if (f1_dec <= f2_dec) {
            return f1;
        } else {
            return f2;
        }
    }
   
    public Fraction add(Fraction frac) {
        int a, b, c, d;
        Fraction sum;
        a = this.getNumerator();
        b = this.getDenominator();
        c = frac.getNumerator();
        d = frac.getDenominator();
        sum = new Fraction(a*d + b*c, b*d);
        return sum;
    }

    public Fraction add(int number) {
        Fraction frac = new Fraction(number, 1);
        Fraction sum = add(frac);
        return sum;
    }

    public Fraction divide(Fraction frac) {
        int a, b, c, d;
        Fraction quotient;
        a = this.getNumerator();
        b = this.getDenominator();
        c = frac.getNumerator();
        d = frac.getDenominator();
        quotient = new Fraction(a*d, b*c);
        return quotient;
    }

    public Fraction divide(int number) {
        Fraction frac = new Fraction(number, 1);
        Fraction quotient = divide(frac);
        return quotient;
    }

    public boolean equals(Fraction frac) {
        Fraction f1 = simplify();
        Fraction f2 = frac.simplify();
        if (f1.getNumerator() == f2.getNumerator() &&
            f1.getDenominator() == f2.getDenominator()) {
            return true;
        } else {
            return false;
        }
    }

    public int getDenominator() {
        return denominator;
    }

    public int getNumerator(){
        return numerator;
    }

    public Fraction multiply(Fraction frac){
        int a, b, c, d;
        Fraction product;
        a = this.getNumerator();
        b = this.getDenominator();
        c = frac.getNumerator();
        d = frac.getDenominator();
        product = new Fraction(a*c, b*d);
        return product;
    }

    public Fraction multiply(int number){
        Fraction frac = new Fraction(number, 1);
        Fraction product = multiply(frac);
        return product;
    }

    public void setDenominator(int denom){
        if (denom == 0) {
            System.err.println("Fatal Error");
            System.exit(1);
        }
        denominator = denom;
    }

    public void setNumerator(int num) {
        numerator = num;
    }

    public Fraction simplify(){
        int num = getNumerator();
        int denom = getDenominator();
        int gcd = gcd(num, denom);
        Fraction simp = new Fraction(num/gcd, denom/gcd);
        return simp;
    }

    public Fraction subtract(Fraction frac) {
        int a, b, c, d;
        Fraction diff;
        a = this.getNumerator();
        b = this.getDenominator();
        c = frac.getNumerator();
        d = frac.getDenominator();
        diff = new Fraction(a*d - b*c, b*d);
        return diff;
    }

    public Fraction subtract(int number) {
        Fraction frac = new Fraction(number, 1);
        Fraction difference = subtract(frac);
        return difference;
    }

    public String toString() {
        return getNumerator() + "/" + getDenominator();
    }

    private double decimal() {
        return (double) getNumerator() / getDenominator();
    }
}

输出:

How many fractions? 3
 1: 28181/38503 simplifies to 28181/38503 // Unsimplified
 2: 75654/99570 simplifies to 12609/16595
 3: 787/31255 simplifies to 787/31255 // Unsimplified
英文:

So I'm writing an assignment for my OOP class that asks the user for a number of fractions, then randomly generates that number of fractions. Part of the assignment states that if one of the fractions cannot be simplified then skip it and create a new fraction that can be simplified. However the unreducible fractions still make it through. I need a way to have the program make a new fraction if the GCD of a fraction is 1.

Code:

import java.util.Random;
// The class is called boxes because I&#39;m supposed to print boxes around the fractions, but I&#39;ll 
implement it later.
class SimpleFracBoxes{
private int numberOfFractions = 0;
private String result = &quot;&quot;;  
Random myRandom = new Random( );
int min = 1;
int max = 100000;
public SimpleFracBoxes( )
{
}
public SimpleFracBoxes(int nOFracs)
{
numberOfFractions = nOFracs;
}
// makes the fractions   
public void makeTheFractions()
{
for (int i = 0; i &lt; numberOfFractions; i++)
{
Fraction frac = getAGoodFraction();
Fraction frac2 = frac.simplify();
result = result + &quot; &quot;+ (int)(i + 1) + &quot;: &quot; + frac + &quot; simplifies to &quot;+ frac2 + &quot;\n&quot; ;         
}
}     
// creates a fraction that can be divided           
private Fraction getAGoodFraction()
{  
Fraction frac;
do {                      
frac = new Fraction (myRandom.nextInt(max-min), myRandom.nextInt(max-min));      
}      
while (frac.getNumerator() &gt;= frac.getDenominator());
int num = frac.getNumerator();
int denom = frac.getDenominator();
int gcd = frac.gcd(num, denom);        
if (gcd == 1)  {                  
getAGoodFraction();
} else if (gcd !=1) {                    
frac.simplify();
}              
return frac;    
}
public String getFractions()
{
return result;
}     
}

Fraction Class code

public class Fraction{
private int numerator;
private int denominator;
public Fraction(){
this(0,1);
}
public Fraction(int number) {
this(number,1);
}
public Fraction(Fraction frac) {
this(frac.getNumerator(), frac.getDenominator());
}
public Fraction(int num, int denom){
setNumerator(num);
setDenominator(denom);
}
public static int gcd(int m, int n) {
int r = n % m;
while (r != 0) {
n = m;
m = r;
r = n % m;
}
return m;
}
public static Fraction min(Fraction f1, Fraction f2) {
double f1_dec = f1.decimal();
double f2_dec = f2.decimal();
if (f1_dec &lt;= f2_dec) {
return f1;
} else {
return f2;
}
}
public Fraction add(Fraction frac) {
int a, b, c, d;
Fraction sum;
a = this.getNumerator();
b = this.getDenominator();
c = frac.getNumerator();
d = frac.getDenominator();
sum = new Fraction(a*d + b*c, b*d);
return sum;
}
public Fraction add(int number) {
Fraction frac = new Fraction(number, 1);
Fraction sum = add(frac);
return sum;
}
public Fraction divide(Fraction frac) {
int a, b, c, d;
Fraction quotient;
a = this.getNumerator();
b = this.getDenominator();
c = frac.getNumerator();
d = frac.getDenominator();
quotient = new Fraction(a*d, b*c);
return quotient;
}
public Fraction divide(int number) {
Fraction frac = new Fraction(number, 1);
Fraction quotient = divide(frac);
return quotient;
}
public boolean equals(Fraction frac) {
Fraction f1 = simplify();
Fraction f2 = frac.simplify();
if (f1.getNumerator() == f2.getNumerator() &amp;&amp;
f1.getDenominator() == f2.getDenominator()) {
return true;
} else {
return false;
}
}
public int getDenominator() {
return denominator;
}
public int getNumerator(){
return numerator;
}
public Fraction multiply(Fraction frac){
int a, b, c, d;
Fraction product;
a = this.getNumerator();
b = this.getDenominator();
c = frac.getNumerator();
d = frac.getDenominator();
product = new Fraction(a*c, b*d);
return product;
}
public Fraction multiply(int number){
Fraction frac = new Fraction(number, 1);
Fraction product = multiply(frac);
return product;
}
public void setDenominator(int denom){
if (denom == 0) {
System.err.println(&quot;Fatal Error&quot;);
System.exit(1);
}
denominator = denom;
}
public void setNumerator(int num) {
numerator = num;
}
public Fraction simplify(){
int num = getNumerator();
int denom = getDenominator();
int gcd = gcd(num, denom);
Fraction simp = new Fraction(num/gcd, denom/gcd);
return simp;
}
public Fraction subtract(Fraction frac) {
int a, b, c, d;
Fraction diff;
a = this.getNumerator();
b = this.getDenominator();
c = frac.getNumerator();
d = frac.getDenominator();
diff = new Fraction(a*d - b*c, b*d);
return diff;
}
public Fraction subtract(int number) {
Fraction frac = new Fraction(number, 1);
Fraction difference = subtract(frac);
return difference;
}
public String toString() {
return getNumerator() + &quot;/&quot; + getDenominator();
}
private double decimal() {
return (double) getNumerator() / getDenominator();
}

}

<!-- language: lang-none -->

Output:
How many fractions? 3
1: 28181/38503 simplifies to 28181/38503 // Unsimplified
2: 75654/99570 simplifies to 12609/16595
3: 787/31255 simplifies to 787/31255 // Unsimplified

答案1

得分: 0

听起来你需要一个分数比较的函数。

// 如果两个分数相同则返回true
public boolean identical(Fraction frac) ...

然后你可以像这样写一个if语句:

if (!frac.identical(frac.reduce())) {
   ... 打印分数 ...
}

另外,我建议将分数化简的逻辑移动到分数类中,这样将来可以在不复制逻辑的情况下重用它。通过将它放在“分数的使用者”中,你有一个“数据结构”,其中“相关逻辑”在其他地方。类最基本的定义是“数据及其密切相关的逻辑”,化简分数与分数非常密切相关,而与将分数存储在数据库中等不太相关。

英文:

It sounds like you need a fraction compare function.

// returns true if two fractions are identical
public boolean identical(Fraction frac) ...

Then you could write a if statement like this

if (!frac.identical(frac.reduce())) {
... print fraction ...
}

Also, I'd consider moving the fraction reduction logic into the fraction, as that way it could be reused in the future without copying the logic. By having it in the "user of the fraction" you have a "data structure" where you "related logic" is somewhere else. The most basic definition of a class is "data with its closely related logic" reducing fractions is very closely related to fractions, and not so closely related to say, storing fractions in a database.

答案2

得分: 0

  • Fraction 类中,未使用的 decimal() 方法被移除。
  • 在 GCD 值为 1 时,不再递归调用 getAGoodFraction() 方法,而是使用循环。
  • 在随机生成的分子大于随机生成的分母时,不再每次创建一个新的 Fraction 对象,而是使用 setNumerator()setDenominator() 方法。这正是它们的用途。
  • getAGoodFraction() 方法中不需要调用 simplify() 方法,只需返回分数。因为 GCD 不等于 1,你知道它可以被简化。

将下面的代码与你的代码进行比较。注意,我添加了一个 main() 方法到 Fraction 类中,以便能够运行代码。并且,我也根据 @KevinAnderson 对你问题的评论,对 gcd() 方法进行了修改。

import java.util.Random;

public class Fraction {
    private int numerator;
    private int denominator;

    public Fraction() {
        this(0, 1);
    }

    public Fraction(int number) {
        this(number, 1);
    }

    public Fraction(Fraction frac) {
        this(frac.getNumerator(), frac.getDenominator());
    }

    public Fraction(int num, int denom) {
        setNumerator(num);
        setDenominator(denom);
    }

    public static int gcd(int m, int n) {
        while (n != 0) {
            int temp = n;
            n = m % n;
            m = temp;
        }
        return m;
    }

    public int getDenominator() {
        return denominator;
    }

    public int getNumerator() {
        return numerator;
    }

    public void setDenominator(int denom) {
        if (denom == 0) {
            System.err.println("Fatal Error");
            System.exit(1);
        }
        denominator = denom;
    }

    public void setNumerator(int num) {
        numerator = num;
    }

    public String toString() {
        return getNumerator() + "/" + getDenominator();
    }

    public static void main(String[] args) {
        SimpleFracBoxes sfb = new SimpleFracBoxes(10);
        sfb.makeTheFractions();
        System.out.println(sfb.getFractions());
    }
}

class SimpleFracBoxes {
    private int numberOfFractions = 0;
    private String result = "";
    Random myRandom = new Random();
    int min = 1;
    int max = 100000;

    public SimpleFracBoxes() {
    }

    public SimpleFracBoxes(int nOFracs) {
        numberOfFractions = nOFracs;
    }

    // 生成分数
    public void makeTheFractions() {
        for (int i = 0; i < numberOfFractions; i++) {
            Fraction frac = getAGoodFraction();
            Fraction frac2 = frac.simplify();
            result += String.format("%" + String.valueOf(numberOfFractions).length() + "d. %5d/%5d simplifies to %5d/%5d%n",
                                    (i + 1),
                                    frac.getNumerator(),
                                    frac.getDenominator(),
                                    frac2.getNumerator(),
                                    frac2.getDenominator());
        }
    }

    // 创建一个可被除的分数
    private Fraction getAGoodFraction() {
        int gcd = 1;
        Fraction frac = new Fraction();
        while (gcd == 1) {
            do {
                frac.setNumerator(myRandom.nextInt(max - min));
                frac.setDenominator(myRandom.nextInt(max - min));
            } while (frac.getNumerator() >= frac.getDenominator());
            int num = frac.getNumerator();
            int denom = frac.getDenominator();
            gcd = Fraction.gcd(num, denom);
        }
        return frac;
    }

    public String getFractions() {
        return result;
    }
}

这是运行上述代码时生成的示例输出。

     1. 64480/84728 simplifies to  8060/10591
2. 33376/79317 simplifies to  4768/11331
3. 50944/97026 simplifies to 25472/48513
4. 21339/45510 simplifies to  7113/15170
5. 35884/38628 simplifies to  8971/ 9657
6. 15148/17199 simplifies to  2164/ 2457
7. 72670/95005 simplifies to 14534/19001
8. 19810/44730 simplifies to   283/  639
9. 61790/63956 simplifies to 30895/31978
10.  4824/ 5352 simplifies to   201/  223
英文:
  • Method decimal() in class Fraction is not used, so I removed it.
  • Rather than recursively call method getAGoodFraction() when the GCD value is 1, use a loop.
  • Rather than create a new Fraction object each time the randomly generated numerator is greater than the randomly generated denominator, use methods setNumerator() and setDenominator(). That's what they're for.
  • There is no need to call method simplify() in method getAGoodFraction(). Just return the fraction. Because the GCD is not equal to 1, you know it can be simplified.

Compare the following code with yours.
Note that I added a main() method to class Fraction so as to be able to run the code. And I also changed method gcd() due to the comment to your question from @KevinAnderson.

import java.util.Random;

public class Fraction {
    private int numerator;
    private int denominator;

    public Fraction() {
        this(0, 1);
    }

    public Fraction(int number) {
        this(number, 1);
    }

    public Fraction(Fraction frac) {
        this(frac.getNumerator(), frac.getDenominator());
    }

    public Fraction(int num, int denom) {
        setNumerator(num);
        setDenominator(denom);
    }

    public static int gcd(int m, int n) {
        int factor = m;
        int r = n % factor;
        while (r != 0  &amp;&amp;  factor &gt; 1) {
            r = n % --factor;
            if (r == 0) {
                r = m % factor;
            }
        }
        return factor;
    }

    public int getDenominator() {
        return denominator;
    }

    public int getNumerator() {
        return numerator;
    }

    public void setDenominator(int denom) {
        if (denom == 0) {
            System.err.println(&quot;Fatal Error&quot;);
            System.exit(1);
        }
        denominator = denom;
    }

    public void setNumerator(int num) {
        numerator = num;
    }

    public Fraction simplify() {
        int num = getNumerator();
        int denom = getDenominator();
        int gcd = gcd(num, denom);

        Fraction simp = new Fraction(num / gcd, denom / gcd);
        return simp;
    }

    public String toString() {
        return getNumerator() + &quot;/&quot; + getDenominator();
    }

    public static void main(String[] args) {
        SimpleFracBoxes sfb = new SimpleFracBoxes(10);
        sfb.makeTheFractions();
        System.out.println(sfb.getFractions());
    }
}

class SimpleFracBoxes {
    private int numberOfFractions = 0;
    private String result = &quot;&quot;;
    Random myRandom = new Random();
    int min = 1;
    int max = 100000;

    public SimpleFracBoxes() {
    }

    public SimpleFracBoxes(int nOFracs) {
        numberOfFractions = nOFracs;
    }

//makes the fractions   
    public void makeTheFractions() {
        for (int i = 0; i &lt; numberOfFractions; i++) {
            Fraction frac = getAGoodFraction();
            Fraction frac2 = frac.simplify();
            result += String.format(&quot;%&quot; + String.valueOf(numberOfFractions).length() + &quot;d. %5d/%5d simplifies to %5d/%5d%n&quot;,
                                    (i + 1),
                                    frac.getNumerator(),
                                    frac.getDenominator(),
                                    frac2.getNumerator(),
                                    frac2.getDenominator());
        }
    }

// creates a fraction that can be divided           
    private Fraction getAGoodFraction() {
        int gcd = 1;
        Fraction frac = new Fraction();
        while (gcd == 1) {
            do {
                frac.setNumerator(myRandom.nextInt(max - min));
                frac.setDenominator(myRandom.nextInt(max - min));
            } while (frac.getNumerator() &gt;= frac.getDenominator());
            int num = frac.getNumerator();
            int denom = frac.getDenominator();
            gcd = Fraction.gcd(num, denom);
        }
        return frac;
    }

    public String getFractions() {
        return result;
    }
}

Here is a sample output produced when running the above code.

<!-- language: lang-none -->

 1. 64480/84728 simplifies to  8060/10591
2. 33376/79317 simplifies to  4768/11331
3. 50944/97026 simplifies to 25472/48513
4. 21339/45510 simplifies to  7113/15170
5. 35884/38628 simplifies to  8971/ 9657
6. 15148/17199 simplifies to  2164/ 2457
7. 72670/95005 simplifies to 14534/19001
8. 19810/44730 simplifies to   283/  639
9. 61790/63956 simplifies to 30895/31978
10.  4824/ 5352 simplifies to   201/  223

huangapple
  • 本文由 发表于 2020年10月24日 21:31:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/64513849.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定