2013-08-30 2 views
-4

Я делаю программу, которая делает 2 случайных целых числа, 1-1000, и видит, если она уже сокращена или нет. Он делает это 1000 раз. Затем я проверяю, была ли вероятность того, что она уже была в сжатых выражениях, и решить для pi (вероятность того, что она уже была в сжатых выражениях, равна 6/(pi^2).java.lang.StackOverflowError с решением для большого числа переменных

Im получает сообщение об ошибке «Исключение в потоке "главный" java.lang.StackOverflowError в Ratio.gcd (Ratio.java:66) в Ratio.gcd (Ratio.java:67)»

здесь полный код

public class Ratio{ 
    protected int numerator; // numerator of ratio 
    protected int denominator; //denominator of ratio 
    public int reduceCount = 0; //counts how many times the reducer goes 

    public Ratio(int top, int bottom) 
    //pre: bottom !=0 
    //post: constructs a ratio equivalent to top::bottom 
    { 
     numerator = top; 
     denominator = bottom; 
     reduce(); 
    } 

    public int getNumerator() 
    //post: return the numerator of the fraction 
    { 
     return numerator; 
    } 

    public int getDenominator() 
    //post: return the denominator of the fraction 
    { 
     return denominator; 
    } 

    public double getValue() 
    //post: return the double equivalent of the ratio 
    { 
     return (double)numerator/(double)denominator; 

    } 
    public int getReduceCount() 
    //post: returns the reduceCount 
    { 
     return reduceCount; 
    } 

    public Ratio add(Ratio other) 
    //pre: other is nonnull 
    //post: return new fraction--the sum of this and other 
    { 
     return new Ratio(this.numerator*other.denominator+this.denominator*other.numerator,this.denominator*other.denominator); 

    } 

    protected void reduce() 
    //post: numerator and denominator are set so that the greatest common divisor of the numerator and demoninator is 1 
    { 
     int divisor = gcd(numerator, denominator); 
     if(denominator < 0) divisor = -divisor; 
     numerator /= divisor; 
     denominator /= divisor; 
     reduceCount++; 
    } 

    protected static int gcd(int a, int b) 
    //post: computes the greatest integer value that divides a and b 
    { 
     if (a<0) return gcd(-a,b); 
     if (a==0){ 
      if(b==0) return 1; 
      else return b; 

     } 
     if (b>a) return gcd(b,a); 
     return gcd(b%a,a); 
    } 
    public String toString() 
    //post:returns a string that represents this fraction. 
    { 
     return getNumerator()+"/"+getDenominator(); 

    } 
} 

другие класс

import java.util.*; 



public class ratio1 { 

    /** 
    * @param args 
    */ 
    public static void main(String[] args) { 
     // TODO Auto-generated method stub 
     int nonReducedCount = 0; //counts how many non reduced ratios there are 
     for(int i =1; i<=1000; i++){ 

      Random rand = new Random(); 
      int n = rand.nextInt(1000)+1; //random int creation 
      int m = rand.nextInt(1000)+1; 
      Ratio ratio = new Ratio(n,m); 
      if (ratio.getReduceCount() != 0){ // if the ratio was not already fully reduced 
       nonReducedCount++; // increase the count of non reduced ratios 
      } 



     } 
     int reducedCount = 1000 - nonReducedCount; //number of times the ratio was reduced already 
     double reducedRatio = reducedCount/nonReducedCount; //the ratio for reduced and not reduced 
     reducedRatio *= 6; 
     reducedRatio = Math.sqrt(reducedRatio); 
     System.out.println("pi is " + reducedRatio); 


    } 



} 

heres строки ошибки, в первом классе Ratio.

if (b>a) return gcd(b,a); 
     return gcd(b%a,a); 
+0

http://stackoverflow.com/questions/4009198/java-get-greatest-common-divisor – dcaswell

ответ

0

Ваш метод gcd() является рекурсивным. Пока у вас нет условия выхода, он будет продолжать называть себя.

Это происходит в вашем коде столько раз, что стек, содержащий вызовы, недостаточно для хранения этой информации, поэтому он выдает StackOverflowError.

Возможно, рекурсия - это не правильный подход, или, может быть, вам нужно убежать от рекурсии в какой-то момент.

Кстати, самая большая проблема, общий делитель был задан ранее, here

0

StackOverflowError, как правило, знак слишком много вложенных вызовов метода. Особенно это происходит при неправильном рекурсивном методе, например gcd().

Либо ваше условие выхода неверно (программа никогда не перестает звонить gcd()), либо решение не может быть найдено рекурсивным методом для данных параметров. В последнем случае вам нужно будет найти лучший алгоритм

Смежные вопросы