Reversed number

I've got to display all of the prime numbers(the numbers MUST have 4 digits),which's reverse is still prime.
Example:1009(prime)----9001(still prime),so I will display 1009.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
  int k,j,i,inv,a,ok,n,stare,q,w;
    for(i=1000;i<=9999;i++)
    {
        a=i;
        j=0;
        k=0;
        ok=0;
        w=0;
        stare=0;
        for(j=1;j<=a;j++)
            if(a%j==0)k++;
        if(k==2)ok=1;
        inv=0;
        //It's correct;At this point I can display all of the 4 digit prime numbers on the screen;
        inv=0;
        n=a;
        while(n)
        {
            inv=inv*10+n%10;
            n=n/10;
        }
        cout<<inv <<" ";
    }

The problem is that I cannot display the reversed number of each prime number.I can't check if 1009 and 9001 are both prime,if I can't display the reversed number(9001),can I?
Please do not use functions:)
what do you mean, don't use functions?

if they all have 4 digits...

char c[5];
char tmp;
sprintf(c, "%i", number);
tmp = c[0];
c[0] = c[3];
c[3] = tmp;
tmp = c[1];
c[1] = c[2];
c[2] = tmp;
number = atoi(c);

but it used 2 C functions. Feel free to rewrite the parts of atoi and sprintf you needed yourself...


you can do all this with string class, vectors, etc (built in reverse even). This C approach is to give the algorithm and to understand what needs to happen with a hands-on approach.

There are other ways. you can peel off the digits with %10, % 100, etc and rebuild it with math instead. That would do it without functions..

int one, ten, hund, thou;
one = number % 10;
ten = (number % 100 )/10;
etc
and
reverse = one*1000+ten*100+...

if you want to get snarky with it, log(base 10) +1 is # of digits you have, so you can extend it for any length value.
Last edited on
Here's how you would print out the reverse of an int.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <cmath>
#include <iostream>

int main()
{
    int num{ 12345 };
    std::cout << "original = " << num << '\n'
    		  << "reversed = ";
    while( num != 0 ) {
    	int digit{ num % 10 };
    	std::cout << digit;
    	num /= 10;
    }
    std::cout << '\n';
}


original = 12345
reversed = 54321


To store it in an int, you would need to use std::pow and possibly std::log10 to get the number of digits.
For example, say our number is 12345, the number of digits would be std::log10( 12345 ) + 1 = 5.
Now to compose 12345 we do:
12345 = 1*10^4 + 2*10^3 + 3*10^2 + 4*10^1 + 5*10^0
Notice the pattern in the exponents. It starts off as 1 less than the number of digits, then decreases until 0. Now we know how to get each digit of an int, in the code I posted above, so you should be able to get the reversed number in an int variable.
Topic archived. No new replies allowed.