Showing all odd numbers instead of prime numbers [closed] - python

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed last year.
Improve this question
def prime_num_gen():
try:
r = int(input('Type in the number till which you want to generate your prime numbers : '))
if r <= 2:
print('There is no prime number smaller than 2, 2 is the smallest prime number')
#A list to store primes
#Storing 2 already, because I need a number to start with
prime_num = [2]
#Counter
#Counter will be divided and if it's a prime; will append it
x = 3
#Starting with 3 cus 2 is already considered
#Having a jump of 2, cus no even num is prime, so considering only odd nums
while x <= r:
for num in range(3,x,2):
if num % x == 0:
x += 2
break
else:
prime_num.append(x)
x += 2
print(prime_num)
except:
print('Please only give input as a number!\nTry again')
For some reason, this code is including all odd numbers as prime numbers. I am complete a novice in coding and even if this seems like a pretty obvious mistake, please tell me so 🙏.
Any help will be appreciated!!

There is a small bug in your code. Instead of the condition
if num % x == 0:
You should do
if x % num == 0:
Since num will always be smaller than or equal to x, so its modulus with x will always give the number once again.

Here is a slightly different implementation that can be faster in different ranges. The basic algorithm is quite simple.
def isprime(n):
for i in range(2,int(n**0.5)+1):
if n%i == 0:
return False
return True
for i in range (1,100):
if isprime(i) == True:
print(i)
It takes O(N log (log N)) time to find all prime numbers less than N.

Related

Why the While loop continues and how to calculate the average based on numbers input? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed last month.
Improve this question
Hi I'm trying to solve this coding homework:
Write a program that always asks the user to enter a number. When the user enters the negative number -1, the program should stop requesting the user to enter a number. The program must then calculate the average of the numbers entered excluding the -1.
I define the while loop to make sure it keeps asking, as:
while n != -1
str(input("enter your number:"))
But whenever I try to input -1, it just keeps on asking to enter the number regardless.
Also, I'm not sure what is the best way to define the average excluding -1, none of the lessons prior to this assignment talked about this. I have Googled about it but none of the examples match this particular assignment, even fumbling around did not help.
Thank you for your help :)
Presumably n is meant to be the user input, but you're never assigning a value to n. Did you mean to do this?
n = str(input("enter your number:"))
Also, you're comparing n to -1, but your input isn't a number; it's a string. You can either convert the input to a number via n = int(input(...)), or compare the input to a string: while n != '-1'.
You could ask for a number the if it is not equal to -1 enter the while loop. So the code would be:
n = float(input("What number?"))
if n != -1:
sum += n
nums_len = 1
while n != -1:
sum += 1
nums_len += 1
n = float(input("What number?"))
print("The average is", str(sum/nums_len))
Thanks everyone, this is the final code with the correct values that gives the average of user inputs
n = float(input("What number?"))
if n != -1:
sum = 0
nums_len = 0
while n != -1:
sum += n
nums_len += 1
n = float(input("What number?"))
print("The average is", float(sum/nums_len))

Python: if-else statement, printing 'Weird' if a given integer is odd or it's even but within a particular range shown below, and 'Not Weird' if not [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I'm trying to create an if-else function which will print 'Weird' if an integer n is odd, 'Not Weird' if it's even and between 2 and 5 inclusive, 'Weird' if it's lies between 6 and 20 and not weird if it's an even integer more than 20. I tried the following code but it wouldn't run, can you tell me what the issue is?
#!/bin/python
import math
import os
import random
import re
import sys
if __name__ == '__main__':
n = int(input().strip())
if n % 2 = 1:
print ("Weird")
else:
if n range(2,5):
print:("Not Weird")
else:
if n range(6,20):
print("Weird")
else:
print("Not Weird")
I hope this helps! If this is not exactly what you were looking for, you can still use my code but reorganize the parts.
n = int(input('Write your number : ').strip())
if n % 2 == 1:
#n is odd
print ("Weird")
else:
#n is even
if 2 <= n <= 5:
#n between 2 and 5 inclusive
print("Not Weird")
elif 6 <= n <= 20:
#n between 6 and 20 inclusive
print("Weird")
elif n > 20:
#n greater than 20
print("Not Weird")
You haven't defined a function.
You forgot to use the word in to check if something is in a range.
You need to use the == operator to check for equality (not = which is assignment).
You also don't really need ranges here, just simple inequality operators. You also don't need any of the modules you imported.
def is_weird(n: int) -> bool:
"""Calculates whether or not a positive integer is 'weird'."""
if n % 2 == 1:
return True
if n <= 5:
return False
if n <= 20:
return True
return False
def print_weirdness(n: int) -> None:
"""Prints whether or not a positive integer is 'weird'."""
print("Weird" if is_weird(n) else "Not Weird")
n = int(input().strip())
print_weirdness(n)

Odd and Even HackerRank challenge [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I'm trying to solve a problem on HackerRank and I sent the code, it worked in amost all the scnarios except for scnario 7 and 3 where they insert 18 and it should return "Weird" and when they insert 20 it should return "Weird" as well according to the website.
The rules of the challenge are:
Given an integer, n, positive number from 1 to 100 , perform the following conditional actions:
If n is odd, print Weird
If n is even and in the inclusive range of 2 to 5, print Not Weird
If n is even and in the inclusive range of 6 to 20, print Weird
If n is even and greater than 20, print Not Weird Input Format
A single line containing a positive integer, .
Constraints
Output Format
Print Weird if the number is weird. Otherwise, print Not Weird.
And my code was:
n = 0
n = int(input('Type a number between 1 and 100: '))
odd = False
even = True
# ODD / EVEN
if (n%2) == 0:
n = even #True
else:
n = odd #False
# Is this odd or is this even?
if n == odd:
print ('Weird')
if n == even > 5 < 20:
print('Weird')
elif n == even > 1 < 6:
print ('Not Weird')
else:
print('Not Weird')
I can't see what I did wrong, can you help me to solve it so it can work in all scnarios?
There's a lot to unpick here. As this is an assignment, I'm not going to print the full solution out here, but I will point out the mistakes you've made so you can come to the correct solution.
First issue: reassigning 'n'.
You assign the value from the input to n, then subsequently replace it with the value of odd or even. This means you have lost the original input number. Instead you should assign the result to a new variable (such as 'isEven').
Second issue: uneccesarry 'if'
The result of 'n%2 == 0' is already True/False, depending if n is an even/odd number. So you can simply assign the result, rather than use an 'if' block.
Third issue: multiple operators
Logical operators have an order of operation, and resolution. The statement 'n == even > 5 < 20' makes no logical sense. Instead you should do independent Boolean comparisons, and join them with "and" or "or". E.g. 'if isEven and n < 5 and n> 20'.

If number is 5609 output is "This number is prime", even though I know it's not a prime number [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
If number is 5609 output is "This number is prime",even though I know it's not a prime number. Why am I getting that output?
With several other casual numbers it works.
number = int(input())
if number <= 1:
print("This number is not prime")
for i in range(2, number):
if number % i == 0:
print("This number is not prime")
break
print("This number is prime")
break
You need to check all the possible factors before declaring number to be prime; you do so as soon as the first value of i (2) does not divide it.
The quickest fix is to move the last print statement out of the body of the loop to an else block following the loop.
number = int(input())
if number <= 1:
print("This number is not prime")
for i in range(2, number):
if number % i == 0:
print("This number is not prime")
break
else:
print("This number is prime")
The else block is only executed if the loop exits "naturally", by exhausting its iterators, rather than by a break statement.
That works only with non-primes which are even numbers. This should work better (last print ouside of for-loop)
number = int(input())
prime = True
if number <= 1:
print("This number is not prime")
for i in range(2, number):
if number % i == 0:
prime = False
print("This number is not prime")
break
# Print this when all numbers are looped.
if prime:
print("This number is prime")

Can This Solution to the Google Foobar "Re-ID" be more efficient? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I'm looking for guidance on a better way to solve Google's Re-ID problem. Instead of typing out the "Re-ID" description here, I will simply list the pertinent parts:
There are 10,000 "Minions" each of which are assigned an integer randomly between 0 and 10000 inclusive.
The Minion will look up his integer as an index in a string of concatenated prime numbers - i.e. 2357111317192329...
His new "ID" is generated by finding the index value in the string according to the Minion's integer assignment and concatenating the next 4 numbers with it - i.e. if the Minion's integer assignment is 3 his new ID would be 71113 (7 is the value at index 3 of the string, then we add the next 4 digits/characters)
To solve this I:
Utilized (thanks again, SO) a function to identify if a number is prime or not: is_prime()
Generated a string of all prime numbers concatenated together which facilitates a Minion with assignment "10000" plus the next 4 characters.
Created a function to generate the new ID based on the Minion's assignment and the string of concatenated values: answer()
import math
def is_prime(n):
if n % 2 == 0 and n > 2:
return False
return all(n % i for i in range(3, int(math.sqrt(n)) + 1, 2))
primes = ''
for i in range(2,21000,1):
if len(primes) < 10005:
if is_prime(i):
primes = primes + str(i)
else:
break
def answer(n):
re_id = primes[n:n+5:1]
return(re_id)
Areas of possible improvement
The 21000 in my for loop is completely arbitrary. By trial and error I found 21,000 facilitates a Minion integer assignment of 10000 plus the 5 additional digits/characters.
Is it necessary to create this long string of concatenated prime numbers before hand? Could it not be done dynamically based on the Minion ID?
Thanks for your insights. Happy Friday.
I have used this code to complete the challenge..
def solution(b):
bag = "2"
for num in range(0,20500):
if num > 1:
for j in range(2,num):
if (num % j) == 0:
break
elif len(bag) >= 10006:
break
elif j==num-1:
bag += str(num)
break
else:
continue
return bag[b:b+5]

Categories

Resources