Skip to content

Latest commit

 

History

History
49 lines (34 loc) · 1.74 KB

File metadata and controls

49 lines (34 loc) · 1.74 KB

7.2 All Prime Numbers

the problem

Ask the user to enter a number. Then find all the primes up to that number.

Hints

You can use the previous is_prime function that you created in the previous problem. Now create a new function named all_primes. In that function, run a for loop.

For each number, call the is_prime function. If the return is True to add it in the prime list.

The Solution

defis_prime(num): foriinrange(2,num): if (num%i) ==0: returnFalsereturnTruedefall_primes(num): primes= [] forninrange(2,num+1): ifis_prime(n) isTrue: primes.append(n) returnprimesnum=int(input("Enter upper limit: ")) primes=all_primes(num) print(primes)

Try it on Programming Hero

Explanation

The first one is the is_prime that you have seen before. Now we created another function named all_primes. In the all_primes function, we create a list named primes to hold the prime numbers. Then run a for loop using range.

The range starts at 2 and runs until num+1 so that it goes until num. We are starting at 2. Because 2 is the first prime number.

Inside the loop, call the is_prime function and check the return. If the return is True then append the n in the primes list.

Then return the primes list.

That’s it.

  Next Page  

tags: programming-heropythonpython3problem-solvingprogrammingcoding-challengeinterviewlearn-pythonpython-tutorialprogramming-exercisesprogramming-challengesprogramming-fundamentalsprogramming-contestpython-coding-challengespython-problem-solving

close