A
A
Anvario02021-12-29 18:40:34
C++ / C#
Anvario0, 2021-12-29 18:40:34

Why doesn't a C program print output?

I wrote a C program that iterates over the powers of 10 and needs to find the smallest such number that is evenly divisible by 19, but the program is silent. What is the problem? I am sure that there is such a number, with n=17, but still I would like to understand why the program does not work.

#include <stdio.h>
#include <math.h>

int main() {
  int n = 0;
  while (1) {
    long long int i = (2 * pow(10, n) - 4);
    if (i % 19 == 0)
    {
      printf("--------%d--------", n);
      break;
    }
    printf("%d", n);
    printf("\t %lld\n", i);
    n++;
  }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
res2001, 2021-12-29
@res2001

Don't use pow. It works with double, and these are floating point numbers. Double has accuracy up to about 15 significant decimal digits, then everything is approximate. https://en.wikipedia.org/wiki/IEEE_754#Basic_and_i...
You have integer arithmetic everywhere - just multiply each iteration by 10. And don't forget to use long long everywhere.
You have already been given an example in one of the previous questions.
And n there is like - 18.

G
galaxy, 2021-12-29
@galaxy

How many more questions do you need to ask about this silly problem?

int main() {
  unsigned long long n = 10;
  int i = 1;
  while (1) {
    if ((2 * n - 4) % 19 == 0)
    {
      printf("--------%d--------", i);
      break;
    }
    printf("%lld", n);
    printf("\t %d\n", i);
    i++;
    n *= 10ull;
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question