Get the last n digits of a long - python

My program asks user to enter a power and how many digits they want. And finds the last that many digits of 2 raised to the power the user entered.
My code looks like this. I am just a beginner in python. I am not getting the output desired.
temp = int(input('Enter the power of the number: '))
temp2 = int(input('Enter the no.of digits you want: '))
temp3 = (2 ** temp) // temp2
temp4 = (temp3 % 100)
print('The last that many digits of the number raised to the power is is:',temp4)

I am assuming you are looking for something like this:
power: 8
digits: 2
2 ^ 8 = 256
last two digits = 56
To do this your code would look like this:
power = int(input('two to the power of '))
digits = int(input('last how many digits? '))
num = 2 ** power # calculate power
num = num % (10 ** digits) # get remainder of division by power of 10
print(num)
Here's another approach:
power = int(input('two to the power of '))
digits = int(input('last how many digits? '))
num = 2 ** power # calculate power
num = str(num) # convert with string to work with
num = num[-digits:] # get last n digits
num = int(num)
print(num)

Related

Printing digits of an integer in order in Python

I want to print the digits of an integer in order, and I don't want to convert to string. I was trying to find the number of digits in given integer input and then divide the number to 10 ** (count-1), so for example 1234 becomes 1.234 and I can print out the "1". now when I want to move to second digit it gets confusing. Here is my code so far:
Note: Please consider that I can only work with integers and I am not allowed to use string and string operations.
def get_number():
while True:
try:
a = int(input("Enter a number: "))
return a
except:
print("\nInvalid input. Try again. ")
def digit_counter(a):
count=0
while a > 0:
count = count+1
a = a // 10
return count
def digit_printer(a, count):
while a != 0:
print (a // (10 ** (count-1)))
a = a // 10
a = get_number()
count = digit_counter(a)
digit_printer(a, count)
I want the output for an integer like 1234 as below:
1
2
3
4
Using modulo to collect the digits in reversed order and then print them out:
n = 1234
digits = []
while n > 0:
digits.append(n%10)
n //=10
for i in reversed(digits):
print(i)
Recursive tricks:
def rec(n):
if n > 0:
rec(n//10)
print(n%10)
rec(1234)
Finding the largest power of 10 needed, then going back down:
n = 1234
d = 1
while d * 10 <= n:
d *= 10
while d:
print(n // d % 10)
d //= 10

I'm trying to do a function that does n+nn+nnn but it returns differently from what I expected. Can someone point out the flaw in my logic?

number = str(input('Please input a number: '))
def add_numbers(number):
sum = 0
for i in range (1,4):
number = number * i
sum += int(number)
return sum
print(add_numbers(number)
Output for range (1,2) in the loop = 5
Output for range(1,3) in the loop = 60
Output for range (1,4) in the loop = 555615
I tried it for cases where the loop iterates only once or twice which results in 5, and 5+55 = 60, respectively. But when I run it for 3 times it returns 555615. I'm guessing that it returns the correct sum which is 615 but is then added with the string 555 (which I don't understand why this does happen.
This should work:
number = str(input('Please input a number: '))
def add_numbers(number):
number = int(number)
sum = 0
for i in range(1,4):
number = number ** i
sum += int(number)
return sum
print(add_numbers(number))
Output:
Please input a number: 5
15655
Instead of number * i you need number to the power of i or number ** i. Also, since you are passing add_numbers a value from input(), number is a string and you need it to be an int which number = int(number) does.
If you want the equation to be n + nn + nnn instead of n * nn * nnn this works:
number = str(input('Please input a number: '))
def add_numbers(number):
number = int(number)
sum = 0
for i in range(1,4):
new = number ** i
sum += int(new)
return sum
print(add_numbers(number))
Output:
Please input a number: 5
155
This is because number is not reset back to 5 after each loop. (As per John Gordon's comment above).
With one small change, the answer you seek can be found.
number = input('Please input a number: ')
def add_numbers(number):
sum_ = 0
for i in range (1,4):
new = number * i
sum_ += int(new)
return sum_
print(add_numbers(number))
sum will be like that = number *1 + number *2 + number *3 ...
and u want = number + number * number + number * number * number
so u should do that :
sum += pow(number,i)

using the calculation number for the next calculation

experts.
I'm trying to define a function (collatz) that:
Asks for a number. If it is even it prints number // 2, if it odd it prints 3 * number + 1. (OK)
The result, whatever it is, must enter a loop until the result is 1. (NOK)
So, i´m not figure out because the result is not used and is in an infinite loop. Any suggestion?
def collatz():
number = int(input('Enter the number: '))
x = number % 2
while number != 1:
if x == 0:
print(f'{number // 2}')
else:
print(f'{3 * number + 1}')
number = number
print(f'{collatz()}')
You need to actually assign the result back to number.
As well:
The divisibility check needs to be in the loop.
The outer print() is not needed.
The f-strings are redundant. print() converts its arguments to string automatically.
def collatz():
number = int(input('Enter the number: '))
while number != 1:
if number % 2 == 0:
number //= 2 # Short for "number = number // 2"
else:
number = 3*number + 1
print(number)
collatz()
Example run:
Enter the number: 3
10
5
16
8
4
2
1

I want to limit (NOT ROUND) floating point numbers to a certain number in PYTHON,

I want floating numbers be limited for example to 8. When I run the below code it gives me 16 floating numbers. For example, x=4 and y=3, it gives 1.3333333333333333. How can I reduce the number of "3"s. NOTE: I DON'T WANT TO ROUND, JUST LIMIT "3"s.
x=int(input())
y=int(input())
print(x/y)
You can easily do that if you
multiply the number by a power of 10
convert the number to int and
at last divide the number by the power of 10
So the code:
def limit_num(num, limit):
num = num * 10**limit
num = int(num)
num /= 10**limit
return num
number = 4/3 # 1.3333333333333333
number = limit_num(number, 5)
print(number) # 1.33333
Or in one line:
def limit_num(num, limit):
return (int(num * 10**limit) / 10**limit)
round will not give you correct result if decimal digits are 999 types.
You should convert float to string and try
def truncate_float_decimal(float_num, truncate_to_digits):
base_length = len(float_num.split('.')[0])+1
base_length += truncate_to_digits
return float((float_num[:base_length]))
truncated_float = truncate_float_decimal("14.999992223",7)
print (truncated_float)

Program that finds a numbers divisor

I've been making my own little program that finds the divisors for an inputted number.
The way it determines if a number can be divided with another number is if the result is an integer. If its a float, it should come out negative.
This is what I've got so far:
# Divider
Number = input("> ")
divider = 1
while True:
Number = int(Number)
divider = int(divider)
result = 0
result = int(result)
result = Number/divider
if isinstance(result, int):
print("{} Y".format(divider))
else:
print("{} N".format(divider))
divider = divider + 1
if divider == Number + 1:
break
The problem is that when I run the program and input a number like "10" which should have more than one divisor (1,2,5,10) it comes out completely negative:
> 10
1 N
2 N
3 N
4 N
5 N
6 N
7 N
8 N
9 N
10 N
>>>
I wonder what I'm doing wrong.
First I'm going to clean up your code:
Number = 15
divider = 1
while True:
if divider == Number + 1:
break
Number = int(Number)
divider = int(divider)
result = Number/divider
if isinstance(result, int):
print("{} Y".format(divider))
else:
print("{} N".format(divider))
divider = divider + 1
Now, what are they all return as negative? Simply because the / division returns a float (i.e. result is a float). What is the correct solution? Use the % modulo to check if the remainder is 0.
Number = 15
divider = 1
while True:
if divider == Number + 1:
break
Number = int(Number)
divider = int(divider)
result = Number%divider
if result == 0:
print("{} Y".format(divider))
else:
print("{} N".format(divider))
divider = divider + 1
Output:
1 Y
2 N
3 Y
4 N
5 Y
6 N
7 N
8 N
9 N
10 N
11 N
12 N
13 N
14 N
15 Y
The division operator / always results in a floating number in Python 3, so the result will never be an instance of an integer.
You should instead use the modulo operator to test if the remainder is 0:
if number % divider == 0:
print("{} Y".format(divider))
else:
print("{} N".format(divider))
I would solve it using modulus. If the remainder is 0 then its divisible otherwise its not. No need to have any int or float checks.
num = input("> ")
#Assuming the num is an integer
divisors = [] #List of divisors
for i in range(1,num):
if num%i == 0:
divisors.append(i)
Output:
>>[1, 2, 5]
for divisor in range(1, number//2+1):
print("{} {}".format(divisor, "Y" if number % divisor == 0 else "N"))
Some additional advice:
Don't use capitals for variable names. It's good practice to name classes with capitals instead (and all-caps for constants).
It is enough to walk until number // 2 (the integer division) because between number // 2 and number there cannot be any more divisors.
DRY - don't repeat yourself (a very general rule in programming): Use the a if b else c operator to avoid repeating the print.
What about you just use modulo like in the following?
result = Number%divider
if result==0:
print("{} Y".format(divider))
num = int(input('Enter a number : '))
div = 1
count = 0
while True:
if(div == num+1):
break
result = num%div
if result == 0:
print('{} -- yes'.format(div))
count+=1
else:
print('{} -- No'.format(div))
div+=1
print('Total number of divisor : ', count)

Categories