I've looked into other solutions online and my own and all of them gave the exact same output, and thats my terminal being spammed with 1's.
this is my code, (I'm very new to coding so please forgive any clear cut mistakes :I)
def decimaltobinary(numb):
bit = []
x = numb // 2
while numb > 1:
y = x // 2
bit.append(y)
this is the code I found online which gave the exact same output
def trans(x):
if x == 0: return [0]
bit = []
while x:
bit.append(x % 2)
x >>= 1
return bit[::-1]
Related
I am trying to solve this problem on SPOJ, https://www.spoj.com/problems/LASTDIG/ , I am sure the code is correct but when I submit it on the site it shows, time limit exceeded,
The solution code for the problem is:
t=int(input()) #for test cases
for i in range(0,t):
x,y=input().split() #for two seperate input
a=int(x)
b=int(y)
if 0<=a<=20 and 0<=b<=2147483000: #conditions for input
z=x**y
c=str(z)
print(c[-1]) #finally to print the last digit of the number
I suspect maybe the program is too simple and time taking for larger inputs? So, can anyone please suggest how to improve the solution or do I need to choose a different language like C++?
It's not python due to which you are getting TLE, it's due to the approach that you are applying for this question.
You can solve this question using a technique called Binary Exponentiation.
Read about it from here and try to code the solution yourself.
code:
# calculates (x ^ y) % m using binary exponentiation
def binpow(x, y, m) :
x = x % m
ans = 1
while y > 0 :
if y % 2 == 1 :
ans = (ans * x) % m
x = (x * x) % m
y = y >> 1
return ans
for _ in range(int(input())) :
a, b = map(int, input().split())
print(binpow(a, b, 10))
This question already has answers here:
Typecasting to 'int' in Python generating wrong result
(2 answers)
Closed 4 years ago.
I'm working with my own 91-numbers numerical system (unnonagesimal) in python 3.6 for RSA algorithm for my studies project. It works really fine but not with large numbers. Numbers I need it to work with are bigger than 1024 bits.
It doesn't work with some numbers, especially with those big ones.
The question is: Why doesn't it work?
Here's my code:
_unnonagesimal = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.-:+=^/*?&<>()[]#%$#,;'`~|\"\\_"
def unnonagesimal_to_decimal(s):
return sum([_unnonagesimal.find(var) * len(_unnonagesimal) ** i
for i, var in enumerate(reversed(s))])
def decimal_to_unnonagesimal(n):
if n == 0:
return 0
else:
s = ""
while n != 0:
s += _unnonagesimal[n % len(_unnonagesimal)]
n = int(n / len(_unnonagesimal))
return s[::-1]
Where:
unnonagesimal_to_decimal(s) converts unnonagesimal string s into a decimal number.
and
decimal_to_unnonagesimal(n) converts decimal int n into an unnonagesimal number.
Alright, I just find out thanks to #user2357112
The problem was with int(blah / blah).
Corrected to int(blah // blah).
Now works fine.
This problem was becasue I switched to python 3 from python 2.
For anyone who doesn't know: in python 2, 5/2 = 2 but in python 3, 5/2 = 2.5 yet 5//2 = 2
I just thought dividing integers are the same in python 2 and 3.
Working code in python 3.6.5:
_unnonagesimal = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.-:+=^/*?&<>()[]#%$#,;'`~|\"\\_"
def unnonagesimal_to_decimal(s):
return sum([_unnonagesimal.find(var) * len(_unnonagesimal) ** i for i, var in enumerate(reversed(s))])
def decimal_to_unnonagesimal(n):
if n == 0:
return 0
else:
s = ""
while n != 0:
s += _unnonagesimal[n % len(_unnonagesimal)]
n = int(n // len(_unnonagesimal))
return s[::-1]
So I was studying recursion function online. And the one question asks me to write a function to add up a number's digits together. For example (1023) -> 1 + 0 + 2 + 3 = 6. I used % and // get get rid of a digit each time. However, I don't know how to add them up together. The closest I can get is to print out each digit. Can anyone help me solve it or give me a hint please?
def digitalSum(n):
if n < 10:
sum_total = n
print(sum_total)
else:
sum_total = n % 10
digitalSum((n - (n % 10))//10)
print(sum_total)
digitalSum(1213)
Your function should return the current digit plus the sum of the rest of the digits:
def digitalSum(n):
if n < 10: return n
return n % 10 + digitalSum(n // 10)
print digitalSum(1213)
For completeness, you can also handle negative numbers:
def digitalSum(n):
if n < 0: sign = -1
else: sign = 1
n = abs(n)
if n < 10: return n
return sign * (n % 10 + digitalSum(n // 10))
print digitalSum(1213)
A correct version of your function is as follows:
from math import log10
def sum_digits(n, i=None):
if i is None:
i = int(log10(abs(n)))
e = float(10**i)
a, b = (n / e), (abs(n) % e)
if i == 0:
return int(a)
else:
return int(a) + sum_digits(b, (i - 1))
print sum_digits(1234)
print sum_digits(-1234)
Example:
$ python -i foo.py
10
8
>>>
Updated: Updated to properly (IHMO) cope with negative numbers. e.g: -1234 == -1 + 2 + 3 + 4 == 8
NB: Whilst this answer has been accepted (Thank you) I really think that perreal's answer should have been accepted for simplicity and clarity.
Also note: that whilst my solution handles negative numbers and summing their respective digits, perreal clearly points out in our comments that there are ate least three different ways to interpret the summing of digits of a negative number.
I tried writing a basic program that converted binary to decimal. However, it's not working. Where did I go wrong? What am I missing. Thanks for the help in advance.
n=int(raw_input(' '))
while n = 1:
k = n % 10
z= 0
w=0
w = k * (pow ( 2, z)) + w
z = z+1
n/10
print w
First of all, you used = for a comparison test. Instead, I think that you want to use != (not equal):
while n != 1:
= is only used for assignment.
Also, the line:
n/10
does nothing. Instead, it should be:
n /= 10
which is equivalent to:
n = n / 10
I implemented the Miller-Rabin prime test algorithm found on wikipedia with Python 3.
It seems to be working correctly with most numbers but occasionaly fail on certain numbers.
For example, the prime number 99999999999999997 is judged to be NOT prime.
I implemented the algorithm line by line and I have no clue where the problem is.
Can any one help me ?
Here is my code.
the test input is:
1
99999999999999997
(No empty line between two lines.)
And the expected output should be YES, but it gives NO on my machine.
import random
def isPrime(n, k = 5):
'''
Primality test using Miller-Rabin method.
n The number to test primality.
k The number of M-R test to perform.
'''
if n == 1:
return False
if n == 2 or n == 3:
return True
if n % 2 == 0:
return False
# Calculate d
nn = n - 1
s = 1
while nn % (2 ** s) == 0:
s += 1
s -= 1
d = int(nn / (2 ** s))
for i in range(k):
a = random.randint(2, n - 1)
x = pow(a,d,n)
if x == 1 or x == n - 1:
continue
flag = True
for r in range(1, s):
x = pow(x,2,n)
if x == 1:
return False
if x == n - 1:
flag = False
break
if not flag:
continue
return False
return True
count = int(input())
for i in range(count):
if isPrime(int(input())):
print('YES')
else:
print('NO')
This is an implementation of Miller-Rabin I wrote a while ago. It has never given me an unexpected result -- though that doesn't mean it won't! It is substantially identical to the one you pasted, and it declares 99999999999999997 to be prime. Yours did too, when I tested it -- so that's a second to Mikola's opinion. But see below for one possible problem that I can't easily test... scratch that, I tested it, and it was the problem.
When it comes to primality testing, I'm no expert, but I spent a lot of time thinking about and coming to understand Miller-Rabin, and I'm pretty sure your implementation is spot-on.
def is_prime_candidate(self, p, iterations=7):
if p == 1 or p % 2 == 0: return False
elif p < 1: raise ValueError("is_prime_candidate: n must be a positive integer")
elif p < self.maxsmallprime: return p in self.smallprimes
odd = p - 1
count = 0
while odd % 2 == 0:
odd //= 2
count += 1
for i in range(iterations):
r = random.randrange(2, p - 2)
test = pow(r, odd, p)
if test == 1 or test == p - 1: continue
for j in range(count - 1):
test = pow(test, 2, p)
if test == 1: return False
if test == p - 1: break
else: return False
print i
return True
The one thing I noticed about your code that seemed off was this:
d = int(nn / (2 ** s))
Why int, I thought to myself. Then I realized you must be using Python 3. So that means you're doing floating point arithmetic here and then converting to int. That seemed iffy. So I tested it on ideone. And lo! the result was False. So I changed the code to use explicit floor division (d = nn // (2 ** s)). And lo! it was True.
I am going to reiterate my comment, since my testing seems to indicate your example is working. I strongly suspect that you just mistyped your test case. Maybe you can try taking a second look at it? Here is what I got from running it:
In [12]: millerrabin.isPrime(99999999999999997, 5)
Out[12]: True
EDIT: I just ran the updated version, and here is the output from the console:
1
99999999999999997
YES
Again, this looks correct.
From what I can see, the Miller-Rabin algorithm is only probabilistic. Were you not aware of this, or are you using a modified, non probabilistic version?