Click here to Skip to main content
15,885,777 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Python
def prime(n):
    """Finds the nth prime number as a result of user input"""
    index_list = []
    primes_list = []
    for i in range(1, (n + 1)):
        index_list.append(i)
    for p in range(2, (n + 1)):
        if (n % p == 0):
            primes_list.append(p)

    return primes_list

def main():
    value = int(input("Enter a positional value to find the corresponding prime:"))
    print(prime(value))



Index list is just a list of index values so that I can access the nth prime number.

What I have tried:

Currently I just want to be able to print the primes_list, but it keeps returning n.
Posted
Updated 5-Feb-19 22:51pm
v2
Comments
ZurdoDev 31-Jan-19 8:07am    
Debug your code and see what's happening.

1 solution

You code doesn't try to find prime numbers: it lacks a primality test and the like.
Try
Python
import math

def is_prime(primes_list, n): # primality test
  limit = math.ceil(math.sqrt(n))
  i = 0
  while  primes_list[i] <= limit:
    if  n % primes_list[i] == 0:
      return False
    i += 1
  return True

def primes(n): # returs the list of the first n primes
  primes_list =[2,3,5] # pre-charge 'primes_list' with enough items to make 'is_prime' work

  # test corner cases
  if n < 0:
    return []
  if n < 4:
    return primes_list[0 : n]

  c = 7
  while len(primes_list) < n:
    if is_prime(primes_list, c):
      primes_list.append(c)
    c += 2
  return primes_list


pl = primes(100)
index = int(input("Enter a positional value to find the corresponding prime:"))
if index < 100:
  print(pl[index])
 
Share this answer
 
Comments
Maciej Los 7-Feb-19 4:22am    
5ed!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900