Please help. I have the follow exercise but I can't get my code to work.
For every positive total number n you can determine a unique code consisting of two numbers m and p. That works like this:
Step 1: Write n as a number in the binary system, as a binary number b. See below for explanation.
Step 2: Write b backwards as a binary number a.
Step 3: The number m is the number of zeros with number one starting.
Step 4: You get the number by writing the binary number as a number in the decimal system.
For example, suppose n = 202.
Binary you can write that as 1100010.
If you write that backwards, you get 01010011.
That number starts with 1 times a 0.
If you omit that you get 1010011. Write that again in the decimal system and you get 83.
The AB code of 202 is then the pair 1 and 83.
Write a program that takes a number n in the least of standard input. 0 < n < 1000000000 applies.
The program writes two lines to standard output. On the first line is the number m and on the second the number p.
Example:
Input: 202
Output: 1 83
number = input()
a = f'{int(number):0b}'
a = str(a)
code = []
zeroes = 0
for i in a:
code.append(i)
code.reverse()
while True:
if code[0] == "0":
code.pop(0)
zeroes = zeroes + 1
else:
break
x = ''
for i in range(len(code)):
x = x + code[i]
newnum = int(x ,2)
print(str(zeroes))
print(newnum)
I am not sure but is the fString statement correct? Or should it be like:
f'int({number}):0b'
I am working on a collatz sequence that i have found in a book and i want to input the number but it dosen t work , when i put the number the enter keybord key does not work , have i made something wrong in my program ? :
even = range(0,10**5,2)
odd = range(1,10**5,2)
def collatz_s(num):
while num !=1 :
if num in even :
result = num /2
print(result)
num = result
elif num is odd :
result = num *3+1
num = result
print(result)
num = int(input('choose a random number'))
collatz_s(num)
To check whether a number is odd or even, rather than generating range objects and checking whether a number is in them, look at the remainder in the division by two, which you can get with num % 2. If the remained is 1, it means the number is even. Otherwise, it's odd.
Also, use num // 2 to perform an integer division. That way dividing 16 by 2 will give you 8 (the integer number), instead of 8.0 (the floating point number.) It turns out this is really important here, especially since you're interested in finding the remainder of the division (a concept mainly concerning integer numbers.)
I believe it's quite possible that a rounding error in the floating point division might have put your program into an infinite loop (since a number with a tiny decimal part would not be in either even or odd range.) Or if you were surpassing the limit of your ranges (105) you'd be in the same situation where neither branch matches. Using integer division and checking for even or odd using the remainder should fix both issues.
def collatz_s(num):
while num != 1:
if num % 2 == 0:
num = num // 2
print(num)
else:
num = num * 3 + 1
print(num)
The problem is within your elif block, here elif num is odd : change is to in when dealing with remainder use integer division(//) instead to avoid precision error .
def collatz_s(num):
while num != 1:
if num in even:
result = num // 2
print(result)
num = result
elif num in odd:
result = num * 3 + 1
print(result)
num = result
num = int(input('choose a random number'))
collatz_s(num)
# input 5
# output
16
8
4
2
1
I am currently attempting to write a simple bit of python 3 code that allows the user to tell the program which prime number it wants to find and then return the number to the user. I have hit a roadblock because I need to check if the "newprime" value is in fact a prime, which requires me to divide the value by all the previous prime numbers ("primes") and then checking if the answer is a whole number or not. Here is the current program
import numpy
primes = [2]
print("the how many-th prime would you like to calculate?")
numberOfPrime = int( input() )
x = 0
while x <= numberOfPrime:
notprime = 0 #placeholder, should be all numbers which when divided by any of the set "primes" gives a whole number
while newprime == notprime:
newprime = primes[x] + 1
primes.append(newprime)
print(primes)
x += 1
print(primes[numberOfPrime], " is the ", numberOfPrime, "-th prime number", sep="")
As you can see, I added a comment where I would have to insert the missing part.
How do I best approach this?
I am writing a program for counting number of digits in a non negative integer whose upper bound is 10^{1000000} and has a time limit of 12 seconds
I have declared an array with size 1000000 and the indexes 0,1,2...,1000000 correspond to the number of digits of the number represented by 10^{array index}.
However I am getting Time Limit Exceeded for input ranges close to 10^{10000}.
Please find inline the code for the same:
def Number(x):
a=[0]*(1000000)
for j in xrange(len(a)):
#print j
a[j]=j+1
i=0
flag=0
flagc=0
counter=0
while(i<len(a)-1):
#print x
if (10**i)==x:
print a[i]
flag=1
break
elif x>(10**i) and x<(10**(i+1)):
print a[i]
flag=1
break
i=i+1
if (i==len(a)-1 and flag==0 and x==(10**i)):
print a[i]
number=int(input())
Number(number+1)
Please help as to how to handle large input values for the above as time limit got exceeded is coming for inputs close to 10^10000
OP has stated in a comment that his problem is he needs to take a numerical input in the form of a string, add 1 to it, and return the number of digits.
Adding 1 to a number will change the number of digits IF AND ONLY IF the string is composed completely of 9s. A simple test can achieve this. If it is all 9s, output the string length plus 1, otherwise output the unchanged string length.
num = input()
length = len(num)
if num == '9' * length: # checks if string is all 9's
print(length + 1)
else:
print(length)
By eliminating the need to convert to int and back, we save a lot of time. This code executes in fractions of a second.
The simplest way to do this in pure python is to use len(number) where "number" has the required base.
To the commenters saying that this is an integer, the data being discussed in this question would overflow an integer, and these numbers would have to be represented as a strings in memory due to their length.
As shown above in the comments, math.log10 is not accurate enough for large numbers. Try a while loop:
n = 10 ** 10000 - 1
count = 0
while n > 0:
n //= 10
count += 1
print(count)
Output:
10000
Changing n to 10 ** 10000 outputs 10001 as expected.
EDIT: I found something very surprising (to me, at least):
len(str(n))
is actually EXTREMELY fast! I tested for numbers up to 10^1000000, and it finishes executing in a matter of seconds!
I am now doing the MIT opencourse thing, and already the second assignment, I feel it has left me out in the cold. http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-00-introduction-to-computer-science-and-programming-fall-2008/assignments/pset1a.pdf
The specifics of it, are to write something that can calculate the 1000th prime number. We only know about the print, ==, =, 1=,if, else, elif, while, %, -,+,*,/, commands I think. We also don't yet know about importing libraries.
My Idea of how it would work is to take an odd number and try to divide it by, 3,4,5,6,7,8,9 and if %n !=0, then add a number to NumberofPrimes variable starting with 11 as the base of the tests, and assigning it a base value of 4 at the base of NumberofPrimes, though I don't know if that is even right, because I wouldn't know how to display the 1000th prime number.
Am I close?
The latest incarnation of it is as follows:
##calculate the 1000th prime number
potprime = 3
numberofprime = 1
cycle = if potprime%3 = 0:
break
if potpimre%4 = 0:
break
if potprime%5 = 0:
break
if potprime%6 = 0:
break
if potprime%7 = 0:
break
if potprime%8 = 0:
break
if potprime%9 = 0:
break
numberofprime + 1
potprime + 1
if potprime%2 == 0:
potprime = potprime + 1
if potprime != 0:
cycle
Where exactly am I going wrong? Walk me through it step by step. I really want to learn it, though I feel like I am just being left out in the cold here.
At this point, it would be more beneficial for me to see how a proper one could be done rather than doing this. I have been working for 3 hours and have gotten nowhere with it. If anybody has a solution, I would be more than happy to look at it and try to learn from that.
Looks like I am late
It is quite straight forward that if a number is not divisible by any prime number, then that number is itself a prime number. You can use this fact to minimize number of divisions.
For that you need to maintain a list of prime numbers. And for each number only try to divide with prime numbers already in the list. To optimize further it you can discard all prime numbers more than square root of the number to be tested. You will need to import sqrt() function for that.
For example, if you test on 1001, try to test with 3, 5, 7, 11, 13, 17, 19, 23, 29 and 31. That should be enough. Also never try to find out if an even number is prime. So basically if you test an odd number n, then after that test next number: (n + 2)
Have tested the below code. The 1000th prime number is 7919. Not a big number!!
Code may be like:
from math import sqrt
primeList = [2]
num = 3
isPrime = 1
while len(primeList) < 1000:
sqrtNum = sqrt(num)
# test by dividing with only prime numbers
for primeNumber in primeList:
# skip testing with prime numbers greater than square root of number
if num % primeNumber == 0:
isPrime = 0
break
if primeNumber > sqrtNum:
break
if isPrime == 1:
primeList.append(num)
else:
isPrime = 1
#skip even numbers
num += 2
# print 1000th prime number
print primeList[999]
The following code is gross, but since 1000 is indeed a small index, it solves your problem in a fraction of a second (and it uses only the primitives you are supposed to know so far):
primesFound = 0
number = 1
while primesFound < 1000:
number = number + 1 # start from 2
# test for primality
divisor = 2
numberIsPrime = True
while divisor*divisor <= number: # while divisor <= sqrt(number)
if number % divisor == 0:
numberIsPrime = False
break
divisor = divisor + 1
# found one?
if numberIsPrime:
primesFound = primesFound + 1
print number
You can test the solution here.
Now you should find a more efficient solution, optimize and maybe go for the 1000000-th prime...
For one thing, I'm pretty sure that in Python, if you want to have an if statement that tests whether or not A = B, you need to use the == operator, rather then the =.
For another thing, your algorithm would consider the number 143 to be prime, even though 143 = 11 * 13
You need keep track of all the prime numbers that you have already computed - add them to an array. Use that array to determine whether or not a new number that you are testing is prime.
It seems to me that you are jumping into the deep-end after deciding the kiddy-pool is too deep. The prime number project will be assignment 2 or 3 in most beginning programming classes, just after basic syntax is covered. Rather than help you with the algorithm (there are many good ones out there) I'm going to suggest that you attempt to learn syntax with the python shell before you write long programs, since debugging a line is easier than debugging an entire program. Here is what you wrote in a way that will actually run:
count = 4
n = 10 #I'm starting you at 10 because your method
#says that 2, 3, 5, and 7 are not prime
d = [2, 3, 4, 5, 6, 7, 8, 9] #a list containing the ints you were dividing by
def cycle(n): #This is how you define a function
for i in d: #i will be each value in the list d
if not n%i: #this is equal to if n%i == 0
return 0 #not prime (well, according to this anyway)
return 1 #prime
while count < 1000:
count += cycle(n) #adds the return from cycle to count
n += 1
print n - 1
The answer is still incorrect because that is not how to test for a prime. But knowing a little syntax would at least get you that wrong answer, which is better than a lot of tracebacks.
(Also, I realize lists, for loops, and functions were not in the list of things you say you know.)
Your code for this answer can be condensed merely to this:
prime_count = 1
start_number = 2
number_to_check = 2
while prime_count <= 1000:
result = number_to_check % start_number
if result > 0:
start_number +=1
elif result == 0:
if start_number == number_to_check:
print (number_to_check)
number_to_check +=1
prime_count +=1
start_number =2
else:
number_to_check +=1
start_number = 2
To answer your subsequent question, 'How do I keep track of all the prime numbers?
One way of doing this is to make a list.
primeList = [] # initializes a list
Then, each time you test a number for whether it is prime or not, add that number to primeList
You can do this by using the 'append' function.
primeList.append( potprime ) # adds each prime number to that list
Then you will see the list filling up with numbers so after the first three primes it looks like this:
>>> primeList
[11, 13, 17]
Your math is failing you. A prime number is a number that has 2 divisors: 1 and itself. You are not testing the numbers for primality.
I am very late on this but maybe my answer will be of use to someone. I am doing the same open course at MIT and this is the solution I came up with. It returns the correct 1000th prime and the correct 100,000th prime and various others in between that I have tested. I think this is a correct solution (not the most efficient I am sure but a working solution I think).
#Initialise some variables
candidate = 1
prime_counter = 1
while prime_counter < 1000:
test = 2
candidate = candidate + 2
# While there is a remainder the number is potentially prime.
while candidate%test > 0:
test = test + 1
# No remainder and test = candidate means candidate is prime.
if candidate == test:
prime_counter = prime_counter + 1
print "The 1000th prime is: " + str(candidate)
While I was at it I went on and did the second part of the assignment. The question is posed as follows:
"There is a cute result from number theory that states that for sufficiently large n the product of the primes less than n is less than or equal to e^n and that as n grows, this becomes a tight bound (that is, the ratio of the product of the primes to e^n gets close to 1 as n grows).
Computing a product of a large number of prime numbers can result in a very large number,
which can potentially cause problems with our computation. (We will be talking about how
computers deal with numbers a bit later in the term.) So we can convert the product of a set of primes into a sum of the logarithms of the primes by applying logarithms to both parts of this conjecture. In this case, the conjecture above reduces to the claim that the sum of the
logarithms of all the primes less than n is less than n, and that as n grows, the ratio of this sum to n gets close to 1."
Here is my solution. I print the result for every 1,000th prime up to the 10,000th prime.
from math import *
#Initialise some variables
candidate = 1
prime_counter = 1
sum_logs = log(2)
while prime_counter < 10000:
test = 2
candidate = candidate + 2
# While there is a remainder the number is potentially prime.
while candidate%test > 0:
test = test + 1
# No remainder and test = candidate means candidate is prime.
if candidate == test:
prime_counter = prime_counter + 1
# If the number is prime add its log to the sum of logs.
sum_logs = sum_logs + log(candidate)
if prime_counter%1000 == 0:
# For every 1000th prime print the result.
print sum_logs," ",candidate," ",sum_logs/candidate
print "The 10000th prime is: " + str(candidate)
Cheers,
Adrian
I came up with this solution in my interview, but I didn't get the job :( It has about 1/100 less iterations than the solution above:
from math import *
MAX_IDX=1000
MAX_IDX-=1
num_iter=0
l_pirme_list=[3]
candidate=l_pirme_list[0]
prime_counter=1
while prime_counter < MAX_IDX:
candidate+=2
#Cut the binary number in half. This is quite faster than sqrt()
bin_candidate=format(candidate, "2b")
max_prime_search=int(bin_candidate[:len(bin_candidate)/2+1],2)+1
# max_prime_search=sqrt(candidate)+1
candidate_is_prime=1
for prime_item in l_pirme_list:
num_iter+=1
if candidate % prime_item==0:
candidate_is_prime=0
break
elif prime_item > max_prime_search:
candidate_is_prime=1
break
if candidate_is_prime:
prime_counter+=1
l_pirme_list.append(candidate)
l_pirme_list.insert(0,2)
print "number iterations=", num_iter
print l_pirme_list[MAX_IDX]