Math, asked by shivika9934, 1 year ago

How to represent question no 5 i and ii

Attachments:

Answers

Answered by arnav134
0

You need to check all numbers from 2 to n-1 (to sqrt(n) actually, but ok, let it be n). If n is divisible by any of the numbers, it is not prime. If a number is prime, print it.

for num in range(2,101):

prime = True

for i in range(2,num):

if (num%i==0):

prime = False

if prime:

print num

You can write the same much shorter and more pythonic:

for num in range(2,101):

if all(num%i!=0 for i in range(2,num)):

print num

As I've said already, it would be better to check divisors not from 2 to n-1, but from 2 to sqrt(n):

import math

for num in range(2,101):

if all(num%i!=0 for i in range(2,int(math.sqrt(num))+1)):

print num

For small numbers like 101 it doesn't matter, but for 10**8 the difference will be really big.

You can improve it a little more by incrementing the range you check by 2, and thereby only checking odd numbers. Like so:

import math

print 2

for num in range(3,101,2):

if all(num%i!=0 for i in range(2,int(math.sqrt(num))+1)):

print num

Similar questions