-3

My homework is to find the "emirp numbers" (pairs of primes like 13 ⇆ 31) up to 10,000. I can reverse the digits using [::-1], but I must do it with % instead.

Here's my code. It works, but how can I reverse the digits using % instead of [::-1]?

counter=0;
prime_counter=0;
emirp_counter=0;
for N in range(13,9968):
    i=2;
    controlq=1;
    while i < N/2+1 and controlq==1:
        counter+=1;
        if N % i == 0:
            controlq=0;
        i+=1;
    if controlq==1:
        x=int(str(N)[::-1]); # Here's the problem.
        a=2;
        controlw=1
        while a < x/2+1 and controlw==1:
            emirp_counter+=1
            if x % a == 0: 
                controlw=0;
            a+=1
        if controlw==1 and (N!=x):
            prime_counter+=1;
            print(N,'<-- is an emirp number -->',x,);
print('TOTAL PRIME NUMBERS', prime_counter);
print('TOTAL PROCESS', emirp_counter+counter);

I just started learning Python (and programming) 1 month ago.

Mogsdad
  • 44,709
  • 21
  • 151
  • 275
  • 1
    Welcome to StackOverflow! You are more likely to get helpful results if you use punctuation/capitalization in your question. As it stands now, it's far more painful to parse through your question than it is to parse your code. – Jeff Widman Dec 16 '15 at 00:10
  • And where is your actual question? – Julien Dec 16 '15 at 00:10
  • StackOverflow is not a site for homework help. Please read the [how to ask](http://stackoverflow.com/help/how-to-ask) page to learn how to write a good question! – NathanFrasier Dec 16 '15 at 00:14
  • 1
    hint: what does `N%10`, `N%100`, `N%1000` give you? and what about `//` instead of `%` – Julien Dec 16 '15 at 00:32
  • i can get digits of number with using modulus yes but im stucked how i can combine then :D – Erguner Erim Dec 16 '15 at 01:46
  • What's with all the semicolons? They're technically allowed, but utterly unnecessary, and downright irritating to most Python programmers. – Kevin J. Chase Dec 16 '15 at 02:48

2 Answers2

1

reverse a number using mod? from the top of my head I get this

def reverse_number(n):
    digit=[]
    while n!=0:
        n,d = divmod(n,10) # n//10 , n%10
        digit.insert(0,d)
    result=0
    for i,d in enumerate(digit):
        result += d*10**i
    return result

because n mod 10 give my the last digit of the number, then I just have to save it and then do a interger division of the number by 10, and repeat until my number is zero, Python let my do both at the same time with divmod, finally a make the new reversed number adding power of 10 as needed.

>>> reverse_number(45682)
28654
Copperfield
  • 8,131
  • 3
  • 23
  • 29
0

Short answer:

def reverse(x):
    def reverse_int_(n, r):
        return reverse_int_(n / 10, n % 10 + r * 10) if n else r
    return reverse_int_(x, 0)

There you have your % operator.

Luis Masuelli
  • 12,079
  • 10
  • 49
  • 87