python - How to append to a list only the first time a prime is encountered -


I have written this python code, unless all the major numbers print to 1000:

 For prime in  primes = xrange (1, 1000) []: For x in the xchange (2, prime): if (prime% b == 0): brakes and: primes.print (prime) print primes   

However, if a number is prime, then it adds several times before moving to the next number. Tried to use continue instead of br but it does not work

I added some more code to that (which works) just to output the output array in a text file so large that I can not even paste it here here .

How often can I add the prime minister only to the list?

There is a feature in Python that you can use here quite effectively. Just change your indentation in this way: For the prime minister in the xrange (1, 1000)

  primes = []: For x in the xchange (2, prime) for b: if (prime% b = = 0): Brake Braz: Primes.Append (Prime) Print Primes   

That is, the d-indent to else is the same as else < / Code> if not , but for for loop, for a loop in a else branch Which can be executed after the loop, which is Also performs scheduled iterations. If someone is called break , then it is not executed.

You can use it without making too many changes to your original code.

Of course, in your original version, running each loop in which a tested number became a non-prime, which was attached to the test number (which was what you wanted).

Also keep in mind that 1 is not a major number (since at least 1801 in Gauss, some people say that Euclid (600BC) first introduced the prime minister's numbers Was written, though even in the 19th century there were renegades), so your external loop should start with 2 instead.

But note what Daniel wrote in his answer; You do not have to step in the way of the Prime Minister because after reaching the square root of Prime Minister , you can go out. I always compare b * b to prime minister , but maybe computing sqrt (main) is even faster once

And of course, you can be completely faster by ignoring all the numbers too. There are no heads except 2 ; -)

Comments

Popular posts from this blog

ios - Adding an SKSpriteNode to SKScene from a child SKSpriteNode -

Matlab transpose a table vector -

c# - Textbox not clickable but editable -