On Sunday, April 5, 2020 at 8:03:19 PM UTC+5:30, inhahe wrote: > On Sun, Apr 5, 2020 at 8:26 AM Sathvik Babu Veligatla < > sathvikveliga...@gmail.com> wrote: > > > 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 > > > > > > > > Any help is appreciated, > > Thank you. > > -- > > https://mail.python.org/mailman/listinfo/python-list > > > > "l = []" needs to go inside the "while True" loop. as it is, it keeps > adding 1's and 0's to the list with each new "a" value, and then counts the > 1's and 0's, without ever resetting the list back to empty, so once it gets > to 9 the list has a 1 in it and l.count(1) will never be false again. 3, 5 > and 7 are prime so a 1 doesn't get added yet with those values, which is > why 7 is the highest it gets to. so with "l = []" inside the while loop, > "l" would be reset to empty with each new "a" value. > > btw, this is a very inefficient way to compute prime numbers. for example, > why add the 0's to the list? you never count the number of 0's so it's > unnecessary. another example.. why use a list at all? all that matters is > that it find *one* result where a%i==0, it doesn't matter how many results > it found after that, so all you need is a boolean. and you might as well > stop testing a%i for *all* i values up to i, because once it finds the > first result that's 0, you know it's prime so you can just go to the next > number. and you don't need i to go all the way to a, because a%i will > always be > 0 for any i over a/2. and since you're not testing evens, it's > actually any i over a/3. in actuality, though, computing any a%i where i > > the square root of a is redundant because for each factor of a above the > square root of a, you've already tested its cofactor, say a is 100. the > square root of 100 is 10. if you're testing 100%20, that's unnecessary > because 100/20 is 5 and you've already tested 100%5.
thank you buddy, it worked... -- https://mail.python.org/mailman/listinfo/python-list