2016-05-25 16 views
0

私は反復コードに変更したい次の再帰コードを持っています。関数は2つの場所での再帰呼び出しと非常に複雑なので、どこから開始するのかはわかりません。以下の関数に対する反復可能な実装はありますか?反復コードを反復的に書く

int ncip(int dim, double R){ 
    int n, r = (int)floor(R); 

    if (dim == 1) 
     return 1 + 2*r; 
    n = ncip(dim-1, R); // last coord 0 

    for (int i=1; i<=r; ++i){ 
     n += 2*ncip(dim-1, sqrt(R*R - i*i)); // last coord +- i 
    } 

    return n; 
} 
+0

上のいくつかの最適化を行うことができます。https://monsiterdex.wordpress.com/2013/04/05 /整数格子を使用したn次元球面上の整数座標を使用する点の数 - 並列プログラミング部分 - i / –

答えて

2

一般的なアプローチの1つは、関数呼び出しにスタックを使用することです。次のように単純な実装は次のようになり、あなたがまだない場合は、この男のサイトをチェックアウトする必要があり、それ

int ncip(int dim, double R){ 
    typedef pair<int, double> data; // ties parameters into one unit 

    stack<data> s; 
    s.push(make_pair(dim,R)); // push the first set of parameters 
    int n = 0; 

    while(false == s.empty()) { // do the loop until stack is depleted 
     auto item = s.top(); // get the top item and pop it after 
     s.pop(); 
     int r = static_cast<int>(floor(item.second)); 

     if (item.first == 1) { 
      n += 1 + 2*r; 
     } else { 
      s.push(make_pair(item.first-1,item.second)); 

      for (int i = 1; i <= r; ++i){ 
       // since you have a multiplier 2 we push the same parameters twice 
       s.push(make_pair(item.first-1, sqrt(item.second*item.second - i*i))); 
       s.push(make_pair(item.first-1, sqrt(item.second*item.second - i*i))); 
      } 
     } 
    } 
    return n; 
}