Python Forum
python prime number algorithm
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
python prime number algorithm
#1

I have a problem
https://docs.python.org/3/tutorial/controlflow.html
>>>for n in range(2, 10):
     for x in range(2, n):
         if n % x == 0:
             print(n, 'equals', x, '*', n//x)
             break
     else:
         # loop fell through without finding a factor
         print(n, 'is a prime number')
All goes good Rolleyes Rolleyes but when n reaches 9 then how x will be equal to 9, as in all previous steps x will not proceeds from 2. As in simple 9 % 2 == 0 will be false and else part should be execute but Idea Idea here this is calculating 9 % 3 == 0 : and printing the statement. Cry Cry I am stucked Wall Wall here, kindly guide me. Shy Shy
Reply
#2
I don't see anything wrong with your code, except that it could be more efficient. 9 is not a prime number as it is equal to 3 * 3. The output I get is:
2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3
As indicated below the example in the link, the else belongs to the for loop, NOT to the if statement.
Reply
#3
Probably this would help to understand the execution
for n in range(2, 10):
    for x in range(2, n):
        print ('n={}, x={}, n%x={}'.format(n, x, n%x))
        if n % x == 0:
            print('{} equals {} * {}'.format(n, x, n//x))
            break
    else:
        # loop fell through without finding a factor
        print('{} is a prime number'.format(n))
Reply
#4
Got it... Thanks alot guys
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Algorithm for extracting comments from Python source code Pavel1982 6 545 Feb-28-2024, 09:52 PM
Last Post: Pavel1982
  Prime number detector Mark17 5 818 Nov-27-2023, 12:53 PM
Last Post: deanhystad
  Rock paper scissors in python with "algorithm" Agat0 23 6,093 Mar-01-2022, 03:20 PM
Last Post: Agat0
  Pairs of multiplied prime number--->N Frankduc 13 3,559 Jan-16-2022, 01:52 PM
Last Post: Frankduc
  Is 2 a prime number? for loop & range fuction in python docs says yes, mine says no. allusernametaken 4 2,921 Nov-17-2019, 02:56 AM
Last Post: allusernametaken
  check if the number is a prime integer atlass218 5 2,964 Sep-26-2019, 07:58 AM
Last Post: atlass218
  Can Python 3.6 program handle Python 2.7 algorithm? Socrates123 2 1,870 May-14-2019, 09:20 PM
Last Post: snippsat
  Creating a program to look for the largest prime number of a number Wikki14 4 3,921 Sep-08-2018, 12:30 AM
Last Post: Skaperen
  python result problem of an iteration algorithm for power allocation Jessica 1 2,644 Sep-07-2018, 08:08 PM
Last Post: micseydel
  Cage filling algorithm - Python bnbehera 3 3,156 Jul-02-2018, 04:55 PM
Last Post: ichabod801

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020