Home > Back-end >  Using a while loop to check divisibility of a range of numbers
Using a while loop to check divisibility of a range of numbers

Time:03-15

I am trying checking the divisibility of 5 and 7 for the numbers in the range from 1 to 41 using a while loop. I know that there are other options, such as a for loop, but I would like to understand how the code needs to be set up with a while loop. This is the code I wrote:

n = 1
m = 41

div = [5,7]

while(n<=m): 
    if n == 13:
        continue
    if n%div[0]==0 and n%div[1]==0:
        print(n, 'the number is divisible for both 5 and 7')    
    elif n%div[0]==0:
        print(n, 'the number is divisible for 5')    
    elif n%div[1]==0:
        print(n, 'the number is divisible for 7')
    else:
        print(n, 'is divisible for neither 5 or 7')

On the Jupyter session, it didn't return an error, but it takes a significant amount of time to process the output. Can someone tell me how to properly modify this code?

CodePudding user response:

You need to increment n by adding:

n  = 1

at the bottom of the while loop. You also need to remove the continue statement at the top of the body of the while loop. Without these two fixes, the program will attempt to repeatedly check whether a number is divisible by 5 or 7 without ever terminating.


If you must skip a specific number, you should revise the if statement to look like the following:

if n == 13:
    n  = 1
    continue

CodePudding user response:

The continue would block the while loop to go any further when n == 13.

Other than that, the code and algorithm are actually correct. You just forgot to set an incremental structure (n =1).

n = 1
m = 41

div = [5,7]

while(n<=m): 
    if n == 13:
        n =1
    if n%div[0]==0 and n%div[1]==0:
        print(n, 'the number is divisible for both 5 and 7')    
    elif n%div[0]==0:
        print(n, 'the number is divisible for 5')    
    elif n%div[1]==0:
        print(n, 'the number is divisible for 7')
    else:
        print(n, 'is divisible for neither 5 or 7')
    n =1

happy codding :)

edit: correction to the incremental statement and added skip 13 part

CodePudding user response:

Actually, your code will never get out of the while loop. It will always be stuck in the while loop. What you need to rechange the n value in the while loop:

n = 1
m = 41

div = [5,7]

while(n<=m): 
    if n == 13:
        n  = 1
        continue
    if n%div[0]==0 and n%div[1]==0:
        print(n, 'the number is divisible for both 5 and 7')    
    elif n%div[0]==0:
        print(n, 'the number is divisible for 5')    
    elif n%div[1]==0:
        print(n, 'the number is divisible for 7')
    else:
        print(n, 'is divisible for neither 5 or 7')
    n  = 1
  • Related