Reversed Prime Number

Tristan·2024년 6월 29일

If you enter N natural numbers, flip each natural number and write a program that outputs the result if the result is prime. For example, if you flip 32 it is 23, 23 is prime. Then print 23. If you flip 910, you must digitize it as 19. Ignore consecutive zeros from the first digit.

Make sure to write and program the reverse(x), which is an inverting function, and the function defisPrime(x), which checks whether it is a prime number.

Input:

The number of natural numbers N (3<=N<=100) is given in the first row, followed by N natural numbers in the next row. The size of each natural number does not exceed 100,000.

Output:

Outputs flipped prime numbers on the first line. Output order outputs in the order entered.

Input Example:

5
32 55 62 3700 250

Output Example:

23 73

Solution

  • set up a for loop at the bottom that will go through the two functions (reverse, isPrime)

  • the function reverse will reverse the given numbers
    - while x > 0, t = x%10
    - res = res * 10 + t, x = x//10

    • ex) when x = 32, t = 2, res = 0 * 10 + 2 = 2, x = 3
    • x = 3, t = 3, res = 2 * 10 + 3 = 23, x = 0
    • return res = 23
  • the function isPrime will determine whether x is prime number or not
    - check if x == 1 b/c 1 cant be a prime number

    • the for loop goes from 2 to x//2+1 (we only need to check until the half) to check if x has any divisors
      • ex) x = 23
      • if 23 % i (2,3...) == 0: it means x has a divisors, which we return false
  • else, we can return True (return x)

  • Lastly, we want to apply functions into the numbers in a, and if they are pass them, we will return them

n = int(input())
a = list(map(int, input().split()))

def reverse(x):
    res = 0
    while x>0:
        t = x%10
        res = res*10+t
        x = x//10
    return res

def isPrime(x):
    if x == 1:
        return False
    
    for i in range (2, x//2+1):
        if x % i == 0:
            return False
    
    else: 
        return True

for x in a:
    tmp = reverse(x)
    if isPrime(tmp):
        print(tmp, end = ' ')
profile
@Columbia

0개의 댓글