0

I must create a function f(n), which will return a pair of prime numbers with arithmetic average n. For example f(10) = [3, 17], f(3) = [3, 3].

So far I have a problem working at the same time with two prime numbers:

def f(n):
    for i in range(2,a):
        for k in range(2,b):
            if a%i!=0 and b%k!=0:
                n=(a+b)/2
                return [a,b]
f(n)
Artjom B.
  • 61,146
  • 24
  • 125
  • 222
Martin
  • 1
  • 4

2 Answers2

1

First, let's create a function to check if a number is prime (a rather slow one):

def is_prime(n):
    for x in range(2, n):
        if n % x == 0:
            return False
    return True

Then we notice that for two numbers to have average n, they must have sum 2 * n. Also one of the numbers, let's say x will be lower or equal to n. So now it's straightforward:

def f(n):
    for x in range(2, n + 1): # Since smaller will be at most n
        y = 2 * n - x # Since x + y must be 2 * n
        if is_prime(x) and is_prime(y):
            return [x, y]

We can now test:

>>> f(10)
[3, 17]
>>> f(12)
[5, 19]
>>> f(3)
[3, 3]
JuniorCompressor
  • 19,631
  • 4
  • 30
  • 57
0

If I understand correctly, the program only needs to find a pair of prime numbers, so surely you multiply the average (n) by 2, then find all pairs of integers which sum to it, then check if both are primes.

A brute force solution for checking for primes in python is:

def is_prime(n):
    if n==1 or n==0:
        return False
    for i in range(3,n):
        if n%i==0:
            return False
    return True

Other faster solutions and this one can be found here.

Finding pairs of integers that sum to the average times 2 can be done through brute force (this returns each pair twice however):

def sums(n):
    return [[x,n-x] for x in range(1,n)]

Putting it all together, using these two functions:

def f(n):
    for a in sums(n*2):
        if is_prime(a[0]) and is_prime(a[1]):
            return a
    return 'None found'

Hope this is helpful.

Community
  • 1
  • 1
Zarpar
  • 11
  • 4