c - Why this reverse function can not work in the for loop? -
#include <stdio.h> #include <math.h> int prime (long n); long reverse(long n); int main(void) { long n; long i, j; puts("enter n dight number, , find symmetrical prime number"); scanf("%ld", &n); (i = 11; < (pow(10, n) - 1); i+= 2) { if (prime(i)) { j = reverse(i); if (i == j) { printf("%ld\n", i); } } } } int prime (long n) //estimate whether number n primer number { int status = 0; int j; //1 prime, 0 not if (n % 2 == 0 || n == 3) { if (n == 2) status = 1; if (n == 3) status = 1; else { n++; status = 0; } } else { j = 3; while (j <= sqrt(n)) { if (n % j == 0) { status = 0; break; } else status = 1; j+= 2; } } return status; } long reverse(long n) //reverse number { int i, j, x; long k, sum; int digit = 0; int ar[1000]; while (n > 0) { k = n; n = n / 10; x = (k - n*10); digit++; ar[digit] = x; } (i = 1,j = digit - 1; <= digit; i++, j--) { sum += ar[i] * pow(10, j) } return sum; }
i build reverse function in order reverse numbers, example, 214, 412. function works fine in individual number, instance, type reverse(214), return 412, good. when combine reverse()
function loop, function can not work... produces strange number...
so how can fix problem?
the reverse function extremely complicated. better way go be:
long reverse (long n) { long result = 0; while (n != 0) { result *= 10; result += n % 10; n /= 10; } return result; }
i think problem in code in following segment
digit++; ar[digit] = x;
you first increment position assign it, leaving ar[0]
unintialized.
Comments
Post a Comment