A
A
Anvario02021-12-28 14:48:39
C++ / C#
Anvario0, 2021-12-28 14:48:39

Why is the program looping?

Task: Some natural number ends in two. If it is rearranged to the first place, then the number will double. What was the minimum number originally?

My code:
#include <stdio.h>
#include <math.h>

int main() {
  int a = 12;
  int proverka = 0;
  while (1)
  {
    if (a % 10 == 2) {
      int r = a; //Сохраняем начально значение a
      int x = a;
      int count = 0;
      while (x > 0) {
        x /= 10;
        count += 1;  //Считаем, сколько у числа разрядов
      }
      a /= 10;
      a = a + 2 * pow(10, (count - 1));
      if (2 * r == a) {
        printf("r = %d\n", r);
        printf("a = %d\n\n", a);
        proverka = 1;
      }
      a = r;
    }
    a += 10;

    if (proverka == 1) {
      break;
    }
  }
}


Where is the mistake?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
G
galaxy, 2021-12-28
@galaxy

Hint: the number is rather big.

spoiler

Пусть искомое числоa = 10*x + 2
Тогда 2*10^n+x = 2(10*x+2) (переставили 2 в начало, n - число цифр в x)
Т.е. 2*10^n-4 = 19*x - нужно найти n, чтобы 2*10^n-4 делилось на 19.
Напишите такую программу

R
redcircle, 2021-12-28
@redcircle

The answer is 105263157894736842
No wonder the program hangs.
The correct search is:

long long q = 20;
while ((q-4) % 19) q *= 10;
long long answer = ((q-4)/19) * 10 + 2;

D
dollar, 2021-12-28
@dollar

Because it 's an endless loop. while (1)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question