1

I'm totally helpless about this, the only solutions I found are using generators (which I don't understand, because I've just started "trying to code").

Here is my code:

x = 9

PrimeCount = 4

PrimeList = [2, 3, 5, 7]

while PrimeCount < 10002:
    if all():
        y == x
        PrimeList.append(y)
        PrimeCount += 1

    x += 2
    y == x

print (x-2)
print (PrimeList)

What I'm trying to do is solve the Project Euler problem no. 7. (finding the 10001st prime), so I want to go through all odd numbers and check, whether they are divisible by every other number I checked earlier.

I know, that this is a very inefficient solution, but it is the only one I figured out by myself.

Thanks in advance!

Kaushik
  • 6,017
  • 5
  • 33
  • 51
Tomáš Král
  • 197
  • 3
  • 11

6 Answers6

1

How do I check if a number is divisible by every number in a list

>>> def divisible(n, lst):
...     return all(map(lambda y: n%y == 0, lst))
...     
>>> divisible(10, [2,5])
True
>>> divisible(10, [2,5, 7])
False

Just check if the modulo of the number for each element in the list is equal to 0

Netwave
  • 23,907
  • 4
  • 31
  • 58
0

This is also a brute force solution, similar that the one you are trying and easier to understand:

primeList = [2]
check = 3

while len(primeList)<6:
    flag = True
    for num in primeList:
        if check%num == 0:
           flag = False
    if flag:
        primeList.append(check)

    check += 2



print primeList[-1]  

primeList: is going to contain all the primes. It should be initialized with the first one (you can initialize it with more but then you should change the check)

primeCount: use the length of the list instead, is easier-> len(primeList).

check: is the number to check (your x). You should start with the next odd number (if 2 if your last number in primeList, check would be 3 and so on)

In the first while check that the length is less than the nth number you are looking for. In the for loop, check is the number is prime or not, and update flag and list in case. Then go to the next odd number.

Finally, print the last element of your prime list.

To know the 10001st prime, while len(primeList)<10001:

cadv
  • 61
  • 1
  • 9
0

A generator could be considerd as a function/subroutine which returns a list, but only does so one element at a time. Thus allowing you to interact with each element indiviually without ever having to store the whole of the list in memory and loop through it.

A prime number generator, idealy, would return the next prime number in the list of all prime numbers. Many functions google just threw at me return a list of prime numbers within a range or up to some max value.

I couldn't quickly find a prime no. generator that was short (to paste in), so let's assume I'm using the Sieve of Erastothenes described by Eli Bendersky in Q567222 simple-prime-generator-in-python. He defines a prime no. generator capable of producing an infinite list called gen_primes(), but any generator where you don't have to provide a range, or upper limit to the values it tries to find primes within would work.

So your code might become :

#<insert def of gen_primes here>
int PrimeCount = 0;

PrimeList = [];

while PrimeCount < 10002:
    prime_no = gen_primes()
    PrimeCount += 1
    PrimeList.append(prime_no)

print (prime_no)
print (PrimeList)

The loop will exit when PrimeList contains 10001 entries and the last prime number returned by the generator is the one you're looking for. Although I would also question the usefulness of then printing a list with 10001 entries without any formatting.

Community
  • 1
  • 1
R.Sharp
  • 286
  • 1
  • 8
0

How do I check if a number is divisible by every number in a list

Do you really mean every, surely to find a prime number you need to know if the number is divisible by any number in the list.

There are going to be neater, or faster, or more elegant solutions available, I've tried to put this one together from your own code and to make it as understandable as possible. However the function I've defined checks to see if a number is divisible by any number in the list as that is what is required for finding prime numbers. It also doesn't check any further numbers in the list once it has found one which the trial number can be divided by. HTH:

x = 9
# PrimeTarget is the nth prime number - the one being searched for.
PrimeTarget = 10001

PrimeList = [2, 3, 5, 7]

def check_prime(guess, primes):
# Routine to check if guess is divisible by any number in primes.
    for prime_no in primes:
        if guess % prime_no == 0:
            # guess is divisible by a prime no.
            # and thus not prime itself.
            return False
    # Only hit the next line if the guess was not divisible
    # by any of the numbers in the list (primes)
    return True

while len(PrimeList) < PrimeTarget:
    if check_prime(x, PrimeList):
        PrimeList.append(x)

    x += 2

print (x)
print (PrimeList)

A potentailly neater function would be :

def check_prime(guess, primes):
    return any( guess % x == 0 for x in primes)

If you really do want to check if a number is divisible by all numbers in a list, change that any to an all

R.Sharp
  • 286
  • 1
  • 8
0

You can try this python code to find all the prime numbers in a given range. With a few modifications you can also check whether the given no is prime or not by checking its presence in the list.

## method for determining the no of prime nos in a given set of integers

till= int(input('the no upto which u want to find the prime numbers : '))
list=[2,3]
for n in range(4,till):
    test=[]
    for l in list:
        a=n%l
        if a!=0:
            test.append(1)
    if sum(test)==len(list):
        list.append(n)
print(list)
-1

I'm going to write the code in C++ but I'm sure you'll be able to understand and implement it:

int x = 9;
int PrimeCount = 4;
bool isPrime;
PrimeList = [2, 3, 5, 7];

While(PrimeCount < 1002) 
{
  for (int i = 0; i < PrimeCount; i++) 
  {
    //Check if multiple of any of the primes in the list
    if (x % PrimeList[i] == o)
      isPrime = false;
    else
      isPrime = true;
  }
  //If not multiple of available primes, add to array and increment PrimeCount
  if (isPrime) 
  {
    PrimeList[PrimeCount] = x;
    PrimeCount++;
  }
  //Increment x and repeat
  x++;
}

I'm only giving you the logic as I'm not sure if you can add elements in an array in the way that I did. Hope this helps.

ytba92
  • 55
  • 10
  • i don't see it as helpful to post an answer in a different language. – dbliss Jul 11 '16 at 09:05
  • Did you read the first line in my answer? I'm assuming this person has sufficient knowledge to understand the logic behind my code and implement it in his own language. And just in case he doesn't understand C++, I left him comments in English. Did you have a hard time understanding it? Was it not straightforward enough? – ytba92 Jul 11 '16 at 13:19
  • i would say your assumption is totally unjustified, of a user w/ a rep of 1. no evidence the user has "sufficient knowledge." the question has a Python tag, and the best answer is likely to be Python-specific -- e.g., make use of the numpy package. i see you are new to SO as well. you will learn how to give appropriate answers. – dbliss Jul 11 '16 at 18:10
  • you might like to check out the code golf SE site to see how different the implementation of the same logic can be in different languages. – dbliss Jul 11 '16 at 18:14