I have a problem with the task. The task is:
We say that number 1 is a super number. If a number x is super, then
the numbers 2x and 3x are also super. For example, since the number 1
is super, then the numbers 2 and 3 are super. As 2 and 3 are super,
then the numbers 4, 6 and 9 are super, and so on. At the same time,
numbers 10 and 7 are not super. Write a program that asks the user to
enter a natural number n. The program prints whether the entered
number is super.
And this is what I have done so far
num = int(input("Enter a natural number "))
if num <= 0:
print("That is not a natural number")
else:
if num % 5 == 0 or num % 7 == 0 or num % 11 == 0 or num % 13 == 0:
print("Number is not super.")
elif num == 1 or num % 2 == 0 or num % 3 == 0 or num % 8 == 0 or num % 9 == 0:
print("Number is super")
else:
print("Number is not super.")
The problem is that for some numbers like 62 it says that it is a super number, but it ain't..
Just following the definition of super number:
def is_super(k):
if k == 1: return True
if k % 2 == 0:
return is_super(k / 2)
if k % 3 == 0:
return is_super(k / 3)
return False
Some testing
print(is_super(9))
True
print(is_super(14))
False
print(is_super(32))
True
print(is_super(62))
False
To me it looks like you jumped in without first figuring out how you'd work it out manually.
Personally, I think the easiest way to start this would be recursively, though it'll be very inefficient with large numbers, so it's up to you if you then want to go and optimise it after doing the first version. I got it working pretty easily, but since it's a problem you need to solve, I'm not going to just copy and paste the answer.
It works something like this (psuedocode):
def is_super(i):
if i is below 1: not a super
if i is 1: is a super
if i is above 1: check if i/2 or i/3 is a super
There are some nice recursive solutions here, I'll propose a non-recursive one. As some of the comments hint, super numbers have a tell-tale factorization: they are all of the form 2x * 3y for x, y >= 0, and every integer of that form is a super number. This should become clear after some study because the only way to get a super number is to multiply an existing one by 2 or 3, and we start with 1. That leads to the following code to test for superness:
def is_super(n: int) -> bool:
if n < 1:
return False
while n % 3 == 0:
n //= 3
return n & (n - 1) == 0; // Suggested by #KellyBundy
I tried to find shortcut way to test for superness but failed to find anything better than this.
num = int(input("Enter a natural number "))
if num <= 0:
print("That is not a natural number")
else:
if num % 3 == 0:
while num % 3 == 0:
num = num / 3
print(num)
if num == 1 or num % 2 == 0 or num % 3 == 0:
print("Number is super")
else:
print("Number is not super")
elif num % 2 == 0:
while num % 2 == 0:
num = num / 2
print(num)
if num == 1 or num % 2 == 0 or num % 3 == 0:
print("Number is super")
else:
print("Number is not super")
else:
print("Number is not super")
This is what I've done so far but I don't think it will work for large numbers ?
Related
Hi I know there are lots of solutions to this problem but I wanted some help finding out why my answer is wrong.
Here's my answer:
number = int(input("enter a number: "))
for n in range(2, number + 1):
for i in range(2, number // 2):
if n == 2:
print(n)
elif n % i == 0:
break
else:
print(n)
Here's the output on my terminal:
> enter a number: 12
2 2 2 2 3 5 5 5 7 7 7 7 9 11 11 11 11
thankss
The problem with your solution is that you haven't set up the inner loop properly. The other problem (the lesser one in my opinion) is that the print is inside of your inner loop which causes the multiple prints.
Here is a proper solution:
for n in range(2, number + 1):
isPrime = True
for i in range(2, n - 1):
if n % i == 0:
isPrime = False
if isPrime:
print(n)
thanks everyone i realised i made a lot of really silly mistakes.
i fixed my code in case anyone else sees this question and wants a solution:
number = int(input("enter the number: "))
for n in range(2, number + 1):
for i in range(2, n):
if n % i == 0:
break
else:
print(n)
I am trying to make this "algorithm", which will take the number and get it down to 4, 2, 1. If anyone have seen the youtube video regarding this math problem, they will understand.
done = False
while True:
num = int(input("Enter a number: "))
if (num % 2) == 0:
print(num/2)
else:
print(num * 3 + 1)
if num == 1 or 2 or 4:
break
The output is this algorithm not repeating itself.
If I type in number 5 it will x3+1, and print only 16. What I want is it doing this, but keep going till the number is either 1,2 or 4. Hope yall can help :D
The error is in line if num == 1 or 2 or 4:. That always evaluates to True and thus breaks your loop.
Your intention is to have if num == 1 or num == 2 or num == 4:. Or if num in (1,2,4): to be more concise.
(Explanation of your mistake: the if statement has an expression that is being tested. You're chaining a couple of expressions with the or operator, resulting in if expr1 or expr2 or expr3. The if-expression is True if any of those OR'd expressions is True.
Your expr1 is num == 1 which is True only if num equals 1.
Your expr2 is 2 which is True always (!).
Your expr3 is 4 which is True always.
So, your if-expression is always evaluating to True.)
It isn't testing for all three of those numbers (1, 2 and 4).
Here's the fixed code:
done = False
while True:
num = int(input("Enter a number: "))
if (num % 2) == 0:
print(num/2)
else:
print(num * 3 + 1)
if num == 1:
break
if num == 2:
break
if num == 4:
break
I think you want to repeat num/2 or num*3+1 every output. If you use odd number like 7, it calculates 22 and 22 is a even number and 22 is calculated 11 and it returns 34 and so on. I figure it out like this. But it always ends with 4 :)
done = False
num = int(input("Enter a number: "))
while True:
if (num % 2) == 0:
num/=2
print(num)
else:
num = num * 3 + 1
print(num)
if int(num) in [1,2,4]:
break
Question:
Given the prime number n, output the number of prime numbers
My code:
def kthPrime(self, n):
if n>10 and n%10 not in [1,3,7,9]:
return 0
if n == 2:
return 1
queue = []
num = 2
while num <= n:
if n%num == 0 and num != n:
return 0
if num>10 and num%10 not in [1,3,7,9]:
num += 1
continue
for i in range(2,num/2+1):
if num%i == 0:
num += 1
break
else:
queue.append(num)
num += 1
seq = queue.index(n) + 1
return seq
Error:
Your code ran too much time than we expected. Check your time complexity. Time limit exceeded usually caused by infinite loop if your time complexity is the best.
My Question: how to improve it
as user #Prune said , please read the guide first.
I'm not going to tell you how to improve your function , but I'm just gonna give you a faster way to see whether a number is prime or not and hopefully you will understand how to use the function that I'm gonna give you to improve your own function.
The source code :
class numChecker:
def is_prime(self,n):
if n == 2:
return True
if n % 2 == 0 or n < 2:
return False
self.square_root = int(n ** (1/2))
for divisor in range(3, self.square_root + 1, +2):
if n % divisor == 0:
return False
return True
I need to print out numbers between 1 and n(n is entered with keyboard) that do not divide by 2, 3 and 5.
I need to use while or for loops and the remainder is gotten with %.
I'm new here and I just don't understand the usage of %?
I tried something like this:
import math
print("Hey. Enter a number.")
entered_number = int(input())
for i in range(1, entered_number):
if i%2 != 0:
print("The number", i, "is ok.")
else:
pass
if i%3 != 0:
print("The number", i, "is ok.")
else:
pass
if i%5 != 0:
print("The number", i, "is ok.")
help?
You need to test for all 3 conditions in one statement, not in 3:
for i in range(1, entered_number):
if i % 2 != 0 and i % 3 != 0 and i % 5 != 0:
print("The number", i, "is ok.")
The and operators here make sure that all three conditions are met before printing.
You are testing each condition in isolation, which means that if the number is, say, 10, you are still printing The number 10 is ok. because it is not divisible by 3. For numbers that are okay, you were printing The number ... is ok. 3 times, as your code tests that it is not divisible by 3 different numbers separately, printing each time.
If something divides by 7 then:
something % 7 == 0
If something divides by 7 and 9 then:
something % 7 == 0 and something % 9 == 0
Conversely, if something divides by 7 or 9 then:
something % 7 == 0 or something % 9 == 0
Something that does not divide by 7 or 9 is given by the expression:
not (something % 7 == 0 or something % 9 == 0)
You don't require the else: pass bits from your code and one if statement with an if-expression that has three %, == bits in it should suffice.
You should probably check the three conditions at the same time:
if i%2 != 0 and i%3 != 0 and i%5 != 0:
print("The number", i, "is ok.")
Otherwise, you would print the same message several times for a single number.
Anyway, for your second question, the% operation is called modulo and it gives you the remainder of a division. For instance, 5%3 = 2 because 5 = 3*1 + 2. And when you check i%2 != 0, you actually check if i can be divided by 2.
print("Hey. Enter a number.")
entered_number = int(input())
for i in range(1, entered_number):
if i%2 != 0 and i%3 !=0 and i%5!=0:
print("The number", i, "is ok.")
a%b returns the remainder when a is divided by b. Example:
>> 5%3
2
What you are doing wrong here is that you are printing after checking a single condition so it will print even if i is divisible by other numbers. For example if i is 3, it will satisfy the first condition and therefore print that the number is ok but it is actually divisible by 3.
I saw you've solved your problem but my answer may worth reading.
This problem is actually doing filtering over a list of numbers 1..n. You can define a base function to test if number x is dividable by number y, and then use this base function to filter the list to get the result.
Here's my version.
import math
from functools import partial
print("Hey. Enter a number.")
entered_number = int(input())
def not_dividable_by(x, y):
return False if x % y == 0 else True
number_list = range(1, entered_number)
for i in [2, 3, 5]:
test_func = partial(not_dividable_by, y=i)
number_list = filter(test_func, number_list)
for number in number_list:
print("%d is OK" % (number,))
SPOJ Prime Generator My python code is giving a Runtime Error NZEC, why?
testcases = raw_input(" ")
def isPrime(n):
result = True
if n != 0 and n != 1 and n % 2 != 0 and n % 5 != 0 and n % 7 != 0 and n % 9 != 0:
if n > 9:
for i in range(11,n):
if isPrime(i):
if n % i == 0:
result = False
return result
else:
return result
else:
return False
for count in range(0,testcases):
m,n = raw_input(" ").split()
m = int(m)
n = int(n)
for i in range(m,n+1):
if isPrime(i):
print i
You are getting a NZEC because of extra white spaces in the input. It's not difficult to design your code to handle such cases. Take the input at once and tokenize it by white spaces. See how I have done it.
def isPrime(n):
result = True
if n != 0 and n != 1 and n % 2 != 0 and n % 5 != 0 and n % 7 != 0 and n % 9 != 0:
if n > 9:
for i in range(11,n):
if isPrime(i):
if n % i == 0:
result = False
return result
else:
return result
else:
return False
def main(): # Don't leave the code in the global namespace, it runs slower
import sys
tokenizedInput = map(int, sys.stdin.read().split()) # Read at once, tokenize
testcases = tokenizedInput[0]
readAt = 1 # Position to begin reading
for count in range(0,testcases):
m,n = tokenizedInput[readAt:readAt+2] # Read the tokenized input
for i in range(m,n+1):
if isPrime(i):
print i
print # You need to separate two outputs by a line
readAt = readAt + 2
main()
This will get you rid of the NZEC. However, your algorithm is both inefficient and incorrect. For the sample input test case of
2
1 10
3 5
Your modified code now outputs
3
3
The expected output
2
3
5
7
3
5
For every number >= 11 you are recursively calling isPrime. If the number is large enough an stack overflow error will occur.
The Prime Generator problem on SPOJ has a large number limit. Try running your program with large numbers, like 999900000 1000000000.