pages:
  • 1
Daneshvar Amrollahi SAYS

Hi. Does anyone know why does not this code work? It stays in a while loop 4 ever.

#include<iostream>
using namespace std;
bool allsame(int a[],int n)
{
int c = 0;
 for (int i=0;i<n;i++)
 {
     for (int j=i+1;j<n;j++)
     {
         if (a[i]==a[j])
            c++;
     }
 }

 if (c==(n*(n-1)/2))
    return true;

 return false;    

}

int main()
{
int n;
while (cin>>n)
{
      if (n==0)
         return 0;

      int a[10000];
      for (int i=0;i<n;i++)
          cin>>a[i];

      int res = 0;


      while (allsame(a,n)==false)
      {
            for (int i=1;i<n;i++)
            {
                if (i!=n-1)
                {
                 a[i] += a[i-1]/2;
                 a[i-1] -= a[i-1]/2;
                 if (a[i-1]%2==1)
                   a[i-1]++;
                }
                else
                {
                    a[0] += a[n-1]/2;
                    a[n-1] -= a[n-1]/2;
                    if (a[n-1]%2==1)
                       a[n-1]++;
                }
            }
            res++;
      }

      cout<<res<<" "<<a[0]<<endl;
}

return 0;
}