On Sun, 05 Apr 2020 19:46:00 +0200 Pieter van Oostrum <piete...@vanoostrum.org> wrote:
> Sathvik Babu Veligatla <sathvikveliga...@gmail.com> writes: > > > hi, > > I am new to python, and i am trying to output the prime numbers > > beginning from 3 and i cannot get the required output. It stops > > after giving the output "7" and that's it. > > CODE: > > a = 3 > > l = [] > > while True: > > for i in range(2,a): > > if a%i == 0: > > l.append(1) > > else: > > l.append(0) > > > > if l.count(1) == 0: > > print(a) > > a = a + 2 > > elif l.count(1) >> 0: > > a = a + 2 [intervening optimizations omitted to conserve electrons] > And you effectively use the counter as a boolean, so replace is by a boolean. > > a = 3 > while True: > is_prime = True > for i in range(2,a): > if a%i == 0: > is_prime = False > # once we found a divisor, it is no use to continue > break > if is_prime: > print(a) > a = a + 2 > > Further optimizations are possible, for example use range(2,a/2) or > even range (2, sqrt(a)). Now if only there were a way to get rid of that extraneous flag and build some sort of "if the loop ran to completion" construct.... a = 3 while True: for i in range(2,a): if a%i == 0: # once we found a divisor, it is no use to continue break else: # magic here! print(a) a = a + 2 The Time Machine Strikes Again, Dan -- https://mail.python.org/mailman/listinfo/python-list