10

Possible Duplicate:
Help with algorithm problem from SPOJ

Came across this interview question. Given two n-digit prime numbers, convert the first prime number to the second changing one digit at a time. The intermediate numbers also need to be prime. This needs to be done in the minimum number of steps (checking for primality and changing a digit are considered steps)

E.g. convert 1033 to 8179 (1033->1733->3733->.......->8179)

Community
  • 1
  • 1
Manas
  • 589
  • 8
  • 18
  • 2
    Is it guaranteed that the solution exists? In other words, are the two n-digit primes picked so that there always exists intermediate prime numbers which form a solution? – randomguy Sep 06 '10 at 18:18
  • 3
    these sorts of questions make me think the interviewer just wants to show how clever *they* are rather than trying to get something useful out of a candidate. – Paul Dixon Sep 06 '10 at 18:20
  • @Paul Dixon exactly what I felt during those 60 mins!!!! – Manas Sep 06 '10 at 18:20
  • 1
    @NullUserException the interviewer told me that she can convert 1033 to 8179 in 8 steps – Manas Sep 06 '10 at 18:22
  • I am just wondering, what kind of job requires you to transform prime numbers this way ... – Brian Rasmussen Sep 06 '10 at 18:24
  • @Brian: none, but many jobs require you to identify that the problem you have at hand is an example of some well-known general problem. – Steve Jessop Sep 06 '10 at 18:25
  • 3
    see this .. http://www.spoj.pl/problems/PPATH/ you can search the resources link to find a solution for it – Ahmed Kotb Sep 06 '10 at 18:25
  • 1
    @Manas: "convert 1033 to 8179 in 8 steps". Did she say how many of those steps were digit-changes, and how many were checks-of-primality? The thing is that digit-changes are a property of the solution, whereas primality-checks are a property of the algorithm which finds that solution. I don't see how the two are co-measurable. – Steve Jessop Sep 06 '10 at 18:29
  • @Ahmed Kotb Thanks for this link!!!! – Manas Sep 06 '10 at 18:29
  • @Steve Jessop No she did not provide me that info. All she gave me was the series of numbers as a hint (see Ahmed's link) – Manas Sep 06 '10 at 18:33
  • @Steve: Sure, but some of the questions seems a bit too far fetched imo. – Brian Rasmussen Sep 06 '10 at 18:34
  • @Brian: Questions which aren't far-fetched are often surrounded by a whole lot of details which are too tedious to solve in an interview. Assuming there's no better solution, an almost-equivalent to this question would be, "do you know anything about graph theory?", except that this question doesn't allow you to lie. – Steve Jessop Sep 06 '10 at 18:37
  • 1
    @Manas: well, without knowing the definition of a "step" which means that series of numbers constitutes "8 steps", I don't think it's possible to answer the question. It's possible your interviewer has made some error in posing it. – Steve Jessop Sep 06 '10 at 18:39
  • prime path algorithm looks for minimum solution, which contains six steps. you seem to suggest that you want to minimize the cost of finding solution. it is impossible to do so using 8 steps with cost you provided: minimal cost is at least 12 (assuming you know exactly the order, unreasonable assumption). you must have misunderstood something – Anycorn Sep 06 '10 at 19:17
  • Related question: http://stackoverflow.com/questions/2205540 – codaddict Sep 06 '10 at 19:29
  • 1
    @randomguy Doubtful. Given a starting number, there are 9N numbers that differs by a digit, and about N/Log N primes, both out of a total of 10^N N-digit numbers. As N grows large it's expected that there are many cases where these two sets are disjoint. – user168715 Sep 06 '10 at 20:14
  • "checking for primality is considered a step" - this makes it completely different from "exact duplicate" question. I'm curious if there is un-close feature on SO. – DK. Sep 10 '10 at 14:22
  • @DK Yes, there is a reopen feature. It takes 5 votes to reopen a question – NullUserException Sep 10 '10 at 18:19

4 Answers4

4

Nice challenge for a rainy Monday evening (it is here, anyway!). This can be done using Dijkstra's algorithm. The first step is to create a graph containing all 4-digit primes. Then use Dijkstra's algorithm to find the shortest path between the start/end primes. Here's an implementation in Python:

#! /usr/bin/python -tt

# run as: findpath start end

import sys

(start, end) = map(int, sys.argv[1:3])

# http://primes.utm.edu/lists/small/10000.txt
f = open("10000.txt", "r")
lines = f.readlines()
f.close
lines = lines[4:-1] # remove header/footer
all = "".join(lines) # join lines
all = all.split()
all = map(int, all)

# only want the 4-digit primes
fourdigit = [p for p in all if 1000 <= p and p <= 9999]

# returns digits in a number
digits = lambda x: map(int, str(x))

# cache of digits for each prime
digits_for_nums = {}

# returns digits in a number (using cache)
def digits_for_num(x):
    global digits_for_nums
    if x not in digits_for_nums:
        digits_for_nums[x] = digits(x)
    return digits_for_nums[x]

# returns 1 if digits are same, 0 otherwise
diff = lambda pair: 1 if pair[0] == pair[1] else 0

# computes number of identical digits in two numbers
def distance(a, b):
    pair = (a, b)
    pair = map(digits_for_num, pair)
    pair = zip(pair[0], pair[1])
    pair = map(diff, pair)
    same = sum(pair)
    return same

# adjacency list representation of graph of primes
edges = {}

# construct graph
for a in fourdigit:
    edges[a] = []
    for b in fourdigit:
        if distance(a, b) == 3:
            edges[a].append(b)

infinity = sys.maxint

def smallest():
    global dist, Q
    minimum = infinity
    which = None
    for v in Q:
        if dist[v] <= minimum:
            which = v
            minimum = dist[v]
    return which

# Dijkstra's algorithm
dist = {}
previous = {}
Q = edges.keys()
for v in Q:
    dist[v] = infinity
    previous[v] = None
dist[start] = 0
while len(Q) > 0:
    u = smallest()
    if dist[u] == infinity:
        break
    Q.remove(u)
    for v in edges[u]:
        alt = dist[u] + 1
        if alt < dist[v]:
            dist[v] = alt
            previous[v] = u

# get path between start/end nodes
num = end
path = [num]
while num != start:
    num = previous[num]
    path.insert(0, num)
print path
Richard Fearn
  • 25,073
  • 7
  • 56
  • 55
3

This is (a special case of) the shortest path problem. You're looking for a minimal path between two specified vertices, through the graph where the vertices are the primes, and vertices are connected by an edge if and only if they differ at exactly one digit when expressed in base 10. All edges have weight 1.

In the absence of a better idea for the particular structure of this special case: for 4 digits this can surely be completed in negligible time with your favourite path-finding algorithm.

Edit: oops, just noticed that "checking for primality" is a step.

I no longer understand the question. How many numbers do you have to "check for primality" in order to produce the chain 1033 -> 1733 -> 3733? If I use a sieve to find all primes less than 10000, how many "steps" has that taken?

Steve Jessop
  • 273,490
  • 39
  • 460
  • 699
0

The best approach is probably depth-first search with iterative deepening, since the minimum number of steps is requested. The initial depth would be the number of digits that are different between the two numbers.

starblue
  • 55,348
  • 14
  • 97
  • 151
0

This can be thought as a graph problem. I would try something along these lines:

  • Generate all N-digit prime numbers (P) without the start prime (A) and end prime (B).
  • Compute hamming distance from A to all P, pick ones that has distance of 1, set them as children of A.
  • Repeat this until all primes from P has put into the graph or a path to B has been found.
  • Take the shortest path from A to B.
randomguy
  • 12,042
  • 16
  • 71
  • 101
  • 1
    The shortest path for the example given actually goes outside the range of primes A ... B: 1033 -> 1733 -> 3733 -> 3739 -> 3779 -> 8779 -> 8179. So I think your first step needs to be, "generate all primes with the specified number of digits". – Steve Jessop Sep 06 '10 at 18:33
  • Good point! Fixed.. thanks. Have an upboat. :) – randomguy Sep 06 '10 at 18:35
  • What if there are no paths in the said graph whose all edges have the Hamming distance 1? – G S Sep 06 '10 at 18:38
  • @Frederick: Then there is no solution. – randomguy Sep 06 '10 at 18:41