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)
Related
I've got 2 problems here.
my first problem is that the code shows me only one time a factor even though it's multiple x times by the same factor. I don't know how to add it to the factor list.
Another problem is I'm not sure in print - how the sep works and how can I write "*" only between elements of factor list.
I can't use any import functions here (intertools, maths etc.)
Please help me.
def factorize(n):
prvocisla = []
faktor = []
#prime numbers
for num in range(1, 2000):
if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
else:
prvocisla.append(num)
count = 0
for i in prvocisla:
if n % i == 0:
count += 1
faktor.append(i)
print(n, " =", *faktor , sep=' *', end='\n')
factorize(360)
My result:
360 * = *2 *3 *5
The right result:
360 = 2 * 2 * 2 * 3 * 3 * 5
I try the count function with adding same factor to the list "count times" but it shows me an Error.
The problem is that in your second 'for' loop you evaluate if there is a prime number in your number, but not how many times it is present.
To do this you need to repeat the cycle every time you find a prime number and divide the initial number by the prime number. this way you will get to 1 and get all the factors in the array.
Here the right code:
def factorize(n):
prvocisla = []
faktor = []
#prime numbers
for num in range(1, 2000):
if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
else:
prvocisla.append(num)
count = 0
t = n # <-- a temporary variable which get n value
while t>1:
for i in prvocisla:
if t % i == 0:
count += 1
faktor.append(i)
t = t/i <-- divide t every time you find a factor
break
print(f"{n!s} = {' * '.join(str(k) for k in faktor)}")
factorize(360)
For the print I use the #CreepyRaccoon suggestion.
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 have a piece of code here where I am creating a logic to be displaying all of the numbers from 2, to my int(input) to be converted to a list and then only display the prime numbers from 2 to my input.
Here is my code:
def display_prime_numbers(maximum):
lst = []
if maximum <= 2:
print('Enter Number Greater Than 2')
maximum = maximum + 1
rng = range(2,maximum)
for index in rng:
print(index, end=' ')
for i in rng:
if (index % i) == 0:
return False
else:
print(f'{index} is a prime number')
This is my output:
Enter Positive Integer Greater Than 2:10
2 3 4 5 6 7 8 9 10
Summary: I'm unable to display my range count loop as a list and am trying to only display my prime number pieces.
i.e. expected:
[2,3,4,5,6,7,8,9,10]
3 is a prime number
5 is a prime number
7 is a prime number
To clarify my comment, your return false statement will end the function. The first time the mod of the index is == 0, then the function will end and the rest of the list will not be evaluated for being prime.
def display_prime_numbers(maximum):
lst = []
if maximum <= 2:
print('Enter Number Greater Than 2')
maximum = maximum + 1
rng = range(2,maximum)
for index in rng:
print(index, end=' ')
for i in rng:
if (index % i) != 0: #Just print here!
print(f'{index} is a prime number')
display_prime_numbers(10)
def collatz(number):
if number % 2 == 0:
print(number // 2)
return number // 2
elif number % 2 == 1:
result = 3 * number + 1
print(result)
return result
#4. zolang n ongelijk is aan 0, niet stoppen.
n = input("invoer: ")
while n != 1:
n = collatz(int(n))
I've got this code, but I only want to print the highest number in place of the whole queue of collatz sequence.
How could I do that?
Your code can be refactored to print the maximum number from the Collatz Sequence as follows:
def collatz(number):
if number % 2 == 0:
return number // 2
else:
return (3 * number) + 1
# Refactored this part because Collatz Conjecture is defined for positive
# numbers only
try:
n = int(input('invoer: '))
if n <= 0:
raise ValueError
except ValueError:
print('Enter a valid positive integer')
# Set a variable to store maximum value
max_num = 0
while n != 1:
# If the current number is bigger than existing maximum number, update it
max_num = max(n, max_num)
n = collatz(int(n))
print('Maximum number is {}'.format(max_num))
Note that I have updated some of your original code so that only positive integer is a valid input. This is because Collatz Conjecture states that the sequence starts with a positive integer.
Also, in the if-else construct, you do not need to write the condition for odd numbers explicitly because if the integer is not even then it must be odd.
Just have a max variable which you update with n, if n is larger than that variable's value:
def collatz(number):
if number % 2 == 0:
return number // 2
elif number % 2 == 1:
return 3 * number + 1
n = input('invoer: ')
m = 0
while n != 1:
if n > m: m = n
n = collatz(int(n))
print('the max was:', m)
With the input 5 gives 16, since 16 is the max of [5, 16, 8, 4, 2, 1].
Today I saw an interesting task. To make a program which outputs all "narcissistic numbers" (all digits are raised to the power of 3). My program has this code
for number in range(1, 408):
result = 0
for digit in str(number):
result += int(digit) ** 3
if result == number:
print(number)
The output is
1
153
370
370
371
407
Why does 370 appear twice?
You should unindent the last if statement, which runs after each digit:
for number in range(1, 408):
result = 0
for digit in str(number):
result += int(digit) ** 3
if result == number:
print(number)
As another answer notes, this can give you false duplicates if there is match in a number with trailing 0's. There is an added danger, though, of false positives if there is a number whose left X digits equal it, but whose total digits do not.
You're checking whether result==number after each digit in the number. You probably want this check in the outer for loop. As it is, it sees that 370 = 3**3 + 7**3, but it is also 3**3 + 7**3 + 0**3, so it's printed on both of those iterations.
Below code will return true or false if number is narcissistic:
def narcissistic(number):
number = str(number)
empty_arr = []
count = 0
for n in number:
n = int(n)
empty_arr.append(n ** len(number))
for n in empty_arr:
count = count + n
count = int(count)
number = int(number)
if count == number:
return True
else:
return False
I've done something like that to solve the problem:
import math;
def narcissistic( n ):
DecimalPlaces = 0 if n == 0 else math.floor(1 + math.log10(n))
soma = 0
digit = 0
NarcissisticSum = 0
i = 0
for i in range(1,DecimalPlaces):
digit = int((n % 10**i - digit) / (10**(i-1)))
NarcissisticSum += digit ** (DecimalPlaces)
lastDigit = int((n - soma) / (10**i))
NarcissisticSum += lastDigit ** (DecimalPlaces)
return NarcissisticSum == n