Melin Ven - 6 months ago 48

C++ Question

I am solving a c++ algorithmic problem and I don't know why I don't get a right answer. The problem consists in : there is given a row of n numbers. The you need to take each number and add the square of its digits till you get the sum 4 or 1. Then you need to print how many times you have added that number. His is an example: you have a row of 2 numbers: 89 and 68. You start with 89:

64 + 81 = 145;(1) 1 + 16 + 25 = 42;(2) 16 + 4 = 20;(3) 4 + 0 = 4;(4)

and we stop because it is 4. We need to print 4 because we added 4 times again and again till we got 4 or 1.The same with 68. My code is in c++ but it uses for files c.

`#include<stdio.h>`

#include<math.h>

FILE *f,*g;

int n,i,a[500],sqr,nr;

int main()

{

f = fopen("unupatru.in","r");

fscanf(f,"%d\n",&n);

for(i=1;i<=n;i++)fscanf(f,"%d",&a[i]);

fclose(f);

for(i=1;i<=n;i++)

{

nr=0;

sqr=0;

while(sqr!=4 || sqr !=1)

{

while(a[i])

{

sqr+=pow(a[i]%10,2);

a[i]/=10;

}

a[i]=sqr;

nr++;

}

g=fopen("unupatru.out", "w");

fprintf(g,"%d\n",nr);

fclose(g);

}

return 0;

}

Please help me

The problem with my code is that when I click on run and compile it doesn't stop running please help

Answer

Not sure is enough but...

You should put `sqr = 0`

also inside the external while and (as pointed by Igor Tandetnik) modify the test using `&&`

instead `||`

Or better: you shuold use `do`

/`while`

(with `sqr=0`

only inside)

```
do
{
sqr=0;
while(a[i])
{
sqr+=pow(a[i]%10,2);
a[i]/=10;
}
a[i]=sqr;
nr++;
}
while(sqr!=4 && sqr !=1)
```