Prime number python nested loops - python-3.x

I am new to python and I am having some problems with this code that should print all the prime numbers that are smaller than 50 using nested loops.
Here is the code:
i = 2
while(i < 50):
j = 2
while(j <= (i/j)):
if not(i%j):
break
j = j + 1
if (j > i/j):
print(i, " is prime")
i = i + 1
Its output is:
2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
23 is prime
29 is prime
31 is prime
37 is prime
41 is prime
43 is prime
47 is prime
So after 3, j should be 2 and i should be 4. Then it's not a prime number, so it goes back to the while loop.
And the process starts over. j and i should be incremented by one. So j should be 3 and i should be 5, 5 is prime, then it increments again to 6.
So j should still be 3 and i should be 6. But (3 <= (6/3)) <-- this is not true, so it goes to if statement and 3 which is j is bigger than 2 which is i/j, which means 6 should be prime.
But it's not. You can tell that by common sense. And I want to know what part I did wrong here. Did I miss any increments here? Thank you.

First of all, I would like to post the correct syntax for the code.
i = 2
while(i < 50):
j = 2
while(j <= (i/j)):
if not(i%j):
break
j = j + 1
if (j > i/j):
print(i, " is prime")
i = i + 1
By writing the code like this, we are able to do several things. The first thing we are able to do is get a nice visual of what is inside of what, instead of assuming anything. The second thing that we are able to do is see what is being incremented where.
Now, let us approach what is going on inside of this code. The first to realize is that we are starting off with i=2. We are then initializing a while loop that is going to stop when i is greater than 50.
So, now we are inside of the first while loop, and the next thing we are doing is calling j. This variable is equal to 2, as we can see. Not only is it equal to 2, but every time we go down to the bottom of this FIRST WHILE LOOP THAT ENDS WHEN i >=50, we go back to the start and reinitialize j to be 2 again.
This means that j is never going to start out to be two, even though we are adding to j in the SECOND (NESTED) while loop.
Everything from here should make sense, if I understood your question right. The only thing that is weird about this code, in my opinion is the:
if not (i%j)
This seems a little odd, for it would be more clerical if it said:
if (i%j == 0):
break
If you have any other questions, please feel free to ask. And if you find this helpful, feel free to accept it as your answer :)

The indented code is as follows.
i = 2
while(i < 50):
j = 2
while(j <= (i/j)):
if not(i%j):
break
j = j + 1
if (j > i/j) :
print(i, " is prime")
i = i + 1
In your code, j is getting initialized to 2 with every increment of i.
See this snippet if not(i%j): break
If any j divides i, the if not(i%j) becomes true and the loop breaks but j <= (i/j) still holds else control wouldn't have entered this loop. So control skips print(i, " is prime")
So only way if(j > i/j) becomes true is when above loop never breaks. That would mean i didn't get any divisor, hence i is a prime.

I made this infinite prime number generator:
def primes_generator():
n = 1
while True:
for x in range(2, n):
if n % x == 0:
#not prime
break
else:
#prime
yield n
n+=1
you can use it like:
primes = primes_iterator()
for prime in primes:
print(i)

Related

Cant figure out conditionals

I'm working on a 30 day of code challenge and passed 5/8 tests on my code and can't figure out the reason it keeps failing
The parameters are that
if N is odd print weird,
if N is even and in the range of 2-5 print not weird
if N is even and in the range of 6-20 print weird
if N is even and greater than 20 print not weird
N = int(input())
if N % 2 == 0 and range(2-5):
print("Not Weird")
elif N % 2 == 0 and range(6-20):
print("Weird")
elif N % 2 == 0 and N > 20:
print("Not Weird")
elif N % 2 == 1 :
print("Weird")
if N % 2 == 0 and range(2-5):
does not do what you think, it should instead be something like:
if N % 2 == 0 and N in range(2, 6):
Specifically:
each sub-condition (on either side of your 'and') should be complete.
range, in your example, was range(-3) since that's what 2-5 gives.
the range is half open, meaning it includes the start but excludes the end.
1) The function range with defined begging and end is a function that takes 2 parameters as argument. Therefore I'd recommend you to use it as range(x,y) instead of range(x-y).
If you use it like range(2-5), you're actually asking for range(-3). When used with only 1 arg, the function range will give you a list of int from 0 up to the input arg.
Regarded that there is no integer greater than 0 and less than -3, then you're getting an empty list.
2) Also, notice that the upper limit is not inclusive:
>>> for i in range(2,5):
... print(i)
...
2
3
4
so you might consider to use range(2,6) for the first case, range(6,21) for the second case and so on and so forth..
To expand on #paxdiablo's answer, you can also use the step argument of range to test for even numbers:
if N in range(2, 6, 2):

How do I make a program that asks the user for a limit and

I've got this code that asks the user for a limit, and then prints out the sequence of square numbers that are less than or equal to the limit provided.
n=int(input("Limit: "))
counter = 2
while counter <= n:
a = counter*counter
counter=a
print(a)
This is my current code, it's meant to work like this:
Max: 100
1
4
9
16
25
36
49
64
81
100
I'm stuck, how do I fix it? Thanks!
First off, you will want to start your counter variable at 1, otherwise you won't be able to get '1' as a square value.
In terms of printing the rest of the values, you will need to do 3 things:
Check if the square of counter is less than the limit.
If it is than the limit, print the result of counter * counter.
Increment counter by 1 <-- This is important!
Incrementing the counter by 1, is going to allow you to check every possible square that could exist below the specified limit. The following code provides a simple way to accomplish this that matches the pseudocode above:
n=int(input("Limit: "))
counter = 1
while counter <= n:
if counter * counter <= n:
print(counter * counter)
counter += 1
Let me know if you have any questions, I'm happy to clarify anything that still isn't making sense!
You're not actually calculating successive squares. You should be finding the square of counter, and then increasing counter by one
n=int(input("Limit: "))
counter = 1
sq = counter**2
while sq <= n:
print(sq)
counter += 1
sq = counter**2
Fun itertools solution:
from itertools import accumulate, count, takewhile
for i in takewhile(n.__gt__, accumulate(count(1, 2))):
print(i)

reset a maximum value within a while loop

I am trying to identify how many times values exceed the previous input. the following code works for 1,7,9,0 (two times 7, exceeds 1, 9 exceeds 7), but fails on 1,5,2,4,3,0. I get that this is because I set the maximum to 5 and of course 2 and 4 are less than 5. I cannot figure out what to do to "reset" maximum back to 1
a = int(input())
counter = 0
highest = 1
while a != 0:
if a > highest:
highest = a
counter += 1
a=int(input())
# need to reset highest to next input of 'a'
print(counter)
Grateful for your patience. Still an oldie seeing whether I am brain-dead yet. Sorry if this is a dumb question, I just don't see it. Also the course I am following intimates that I can't use anything but if, else, while, no lists or anything
first_num = int(input())
incremental_count = 0
while first_numv != 0:
second_num = int(input())
if second_num != 0 and first_num < second_num:
incremental_count += 1
first_num = second_num
print(incremental_count)
Once I solved it my way, this was the answer given which is cleverer and simpler!

Check if number has a digit multiple times

I've come across a puzzling challenge. I have to check if a number contains the same digit multiple times ex. 11, 424, 66 and so on. at first this seems easy enough but i'm having trouble coming up with a logic to check for this. any ideas?
This is what I've got so far. the function takes in a list. (updated)
arr = [[1,20],[1,10]]
for i in arr:
l = list(range(i[0],i[1]))
for num in l:
if num < 11: continue
for c in str(num):
if str(num).count(c) > 1:
# dont know why code is popping off 12 and 13
print(l.pop(num))
If your ultimate goal is simply detecting if there's a double, this function may help:
def has_doubles(n):
return len(set(str(n))) < len(str(n))
The best way I can think about is converting the number to a string and doing a Counter on it
from collections import Counter
a = 98
c = Counter(str(a))
if any(value > 1 for value in c.values()):
print "The number has repeating digits"
#Two-BitAlchemist thanks for the suggestion
looks like you wanted to create your own algorithm probably researching or a student practice well you just have to understand the properties of numbers divided by 10 where 1/10 = 0.1 10/10 = 1 13/10 = 1 reminder 3 13013/10 = 1301 rem 3 hence we can create a function that stores the reminders in an array an check them against the reminder of next number here is the algorithm in python using recursion, you can achieve the same via loops
def countNumber(foundDigits,number):
next_number = int(number/10);
reminder = number % 10;
if(next_number < 1):
for num in foundDigits:
if(num == number or num == reminder):
return True
return False;
foundDigits.append(reminder);
return countNumber(foundDigits,next_number)
example in interpreter could be
digitsFound = list()
countNumber(digitsFound, 435229)
Solved this! I didn't know pop executes based on position not value! remove is a better fit here.
arr = [[1,40],[1,10]]
for i in arr:
l = list(range(i[0],i[1]))
for num in l:
if num < 11: continue
for char in str(num):
if str(num).count(char) < 2: continue
l.remove(num)
break
print(l)
Here is my solution, its simple and works for 2 digit numbers.
nums = list(input().rstrip().split())
def has_doubles(nums):
for number in nums:
if number[0] == number[1]:
print(number)
else:
continue
has_doubles(nums)

while-loop to number 6174

I'am beginner in programming and have struggled for a while with one task.
Want to write a program wich finds out how many iterations is needed to arrive at the number 6174 from the specified number.
For example.: if I take number 2341 and sort it.
1) 4321-1234=3087
2) 8730-378=8352
3) 8532-2358=6174 (in this case it`s needed 3 iterations.)
And I have to use ,,while loop,, that it runs a code until it comes to number 6174 and stops.
I wrote a code:
n =input('write for nummbers ')
n=str(n)
i=0
i+=1 #"i" show how many times iteration happend.
large = "".join(sorted(n, reverse=True))
little = "".join(sorted(n,))
n = int(large) - int(little)
print(n, i)
Can you give mee some hint how I could run it with while loop.
# untested, all bugs are free ;)
n = input('write for nummbers ')
n = int(n) # you need n as a number
i=0
while n != 6174:
i += 1 #"i" show how many times iteration happened.
large = "".join(sorted(str(n), reverse=True))
little = "".join(sorted(str(n),))
n = int(large) - int(little)
print(n, i)

Resources