Why can two sets of the same code produce two different outputs? - jupyter-notebook

I'm making code that can determine whether the number entered by the user is prime or not. But I kept running into a bug that oddly enough, my friend's code didn't, even though our codes was the same down to the letter.
#my friend's
num = int(input())
if num > 1:
for i in range(2,num):
if (num % i) == 0:
print(num,"is not a prime number")
print(i,"times",num//i,"is",num)
break
else:
print(num,"is a prime number")
else:
print(num,"is not a prime number")
#mine
num = int(input())
if num > 1:
for i in range(2,num):
if (num % i) == 0:
print(num,"is not a prime number")
print(i,"times",num//i,"is",num)
break
else:
print(num,"is a prime number")
else:
print(num,"is not a prime number")
If I enter 121 to my friend's code, the output will be:
121
121 is not a prime number
11 times 11 is 121
But if I enter 121 to my code, the output will be:
121
121 is a prime number
121 is a prime number
121 is a prime number
121 is a prime number
121 is a prime number
121 is a prime number
121 is a prime number
121 is a prime number
121 is a prime number
121 is not a prime number
11 times 11 is 121
What's wrong with mine?

Look at your indentation. Your friends code does for or else, your code does if or else. Read more about why else can be used with for here.
#your friend's
...
for i in range(2,num):
if ...
else: # enters when `for` loop breaks
...
#you
...
for i in range(2,num):
if (num % i) == 0:
...
else: # enters when `if` returns false
...

There is indentation issue with your code.
#my friend's
num = int(input())
if num > 1:
for i in range(2,num):
if (num % i) == 0:
print(num,"is not a prime number")
print(i,"times",num//i,"is",num)
break
else:
print(num,"is a prime number")
else:
print(num,"is not a prime number")
Here i
#mine
num = int(input())
if num > 1:
for i in range(2,num):
if (num % i) == 0:
print(num,"is not a prime number")
print(i,"times",num//i,"is",num)
break
else:
print(num,"is a prime number")
else:
print(num,"is not a prime number")

Related

What is wrong with this Python code for finding an Armstrong number?

I'm trying to write a Python program that will return an Armstrong number and the resulting outputs do not meet my expectations. An Armstrong number in a given number base is a number that is the sum of its own digits each raised to the power of the number of digits.
for i in range(0,len(lst)):
lst[i] = int(lst[i])
sum2= 0
for i in range(0,len(lst)):
sum1 = lst[i]*lst[i]*lst[i]
sum2 += sum1
if sum2 == n :
print("Armstrong number")
else:
print("Not an Armstrong number")
Why is this code returning incorrect results?
You need to cast n as answered above!
Also Armstrong number is not just power of 3
The power is equal to number of digits present in the number.
For Eg :
153 has 3 digits 1 5 and 3
so 1^3 + 5^3 + 3^3 = 153
But if number is 4 digit Number then :
Input : 1634
Output : 1634 is an Armstrong Number
1^4 + 6^4 + 3^4 + 4^4 = 1634
and so on!
So basically the power is no. of digits present in the given no.
Here is my simple piece of code for it :
def Armstrong(num):
exp = len(num)
res = 0
for i in num:
res += pow(int(i),exp)
if res == int(num):
print(num + " is an Armstrong Number")
else:
print(num + " is not an Armstrong Number")
num=input("Enter a number : ")
Armstrong(num)
You are very, very close. The only problem is that n is a string, not an int, so when you compare it to sum2 it will never be equivalent. Cast n to an int and problem solved:
if sum2 == int(n):
If you want to see a more streamlined way to get the same result, here is an example:
value_string = input("Enter an integer value: ")
starting_value = int(value_string)
digits = [int(char) for char in value_string]
cubed_sum = sum([
one_digit ** 3
for one_digit in digits
])
if cubed_sum == starting_value:
print(f"{starting_value} is an Armstrong number.")
else:
print(f"{starting_value} is not an Armstrong number.")

Function that will return the biggest number of consecutive 0's

For a homework problem, in python we are asked to define in a recursive way a function that will return the biggest number of consecutive 0's in binary for any the number n. We need to use "&" and ">>".
For example, the function should return 2 for n = 44 because its binary representation is 101100.
I do not know where to go from here. Any help would be appreciated!
def max_consecutive_zero_iterative(n):
res = 0
streak = 0
while n > 0:
if n & 1:
streak = 0
else:
streak += 1
n = n >> 1
res = max(res, streak)
return res
def max_consecutive_zero_recursive(n):
if n == 0: # end of recursion
return 0
value = max_consecutive_zero_recursive(n >> 1) # call to recursive
current_streak = value & 0xff # current streak is stored in the lowest 8 bits
longest_streak = value >> 8 # longest streak is stored in the upper bits
if n & 1: # if we have a bit set
return max(longest_streak, current_streak) << 8 # we just return the max value between current_streak and longest_streak, stored in upper bits
# else if the bit is not set
current_streak += 1 # we increase our current streak by 1
# and return the max between the longest_streak and current_streak in the upper bits...
return max(longest_streak, current_streak) << 8 | current_streak
# ... but this time we keep information (we don't reset) about the current_streak stored in the lowest 8 bits.
def main():
print(max_consecutive_zero_recursive(0b1000101111000110000000100110) >> 8)
if __name__ == "__main__":
main()

How to factorize a number in Julia?

I am trying to build a function to factorize a number. in this example I used the number 95 and a list of prime numbers. The result should be (5, 19). What am I doing wrong?
function factorize(number, primes)
global factor = Int64[]
for i in primes
while number % primes[i] == 0
push!(factor, primes[i])
number = number ÷ primes[i]
end
if number ÷ primes[i] != 1
break
end
end
return factor
end
number = 95
primes = (2,3,5,7,11,13,17,19,23, 27, 31)
answer = factorize(number, primes)
println(answer)
This is a fixed function:
function factorize(number, primes)
factor = Int64[]
for p in primes
while number % p == 0
push!(factor, p)
number = number ÷ p
end
if number == 1
break
end
end
if number > 1
#warn "factorization failed, not enough primes passed; printing only factors found in primes vector"
end
return factor
end
Changes:
you do not need global qualifier
writing p in primes returns you the elements of primes not the index into primes
the termination condition should be number == 1
error handling if primes vector does not contain all primes that are required
Note that you can compare your results with function factor from Primes.jl package (but I guess you wanted this code as an algorithmic problem).

Why is my recursive function in python 3.6 returning two results?

I wrote this program in python to find the factorial of given input n:
def factorial(n):
count = n
if n == 1:
return n
else:
while count != 0:
return n * n-1
n -= 1
count -= 1
When I run it multiple times, it comes up with multiple answers for the same input. For example, I will run it at n = 5 and it returns 120 sometimes and 24 other times. This holds true for all of the numbers that I have tried. Why is this so?
Thanks!
You have error in logic. First of all, you are multiplying n by itself, and deduce 1 from it (missing brackets). Second, you should call factorial function recursively, in which case you don't need extra variable (count) and don't need while loop:
def factorial(n):
if n <= 1:
return 1
else:
return n * factorial(n-1)
The logic is wrong overall. When you pass 5 every single time the result will be 24 the reason is return n * n-1 part. In the loop it should be n*=n-1 instead of return n * n-1 Also your loop must be while n>1 and remove count at all. Good luck at school :)
def fact(n):
if n<=1:
return 1
else:
return n * fact(n-1)

calculating prime factors in 'R'

I am very new to 'R' and am trying to start learning it. I have written the following program to generate the prime factors of a given number. But for mysterious reasons it generates a nonsense list at the end of the day. I cannot find where or why this is happening. Please can you help.
library(gmp)
getPrimeFactors = function(n){
primeList=c()
if(isprime(n)){
primeList <- append(primeList, n)
return (primeList)
}
currentPrime <- 2
while(TRUE){
# Check if input is divisible by the current primeList
if(n %% currentPrime == 0){
cat(sprintf("the number %f is divisible by %f\n", n, currentPrime))
n = n%/%currentPrime
cat(sprintf("current prime :%f\n", currentPrime))
primeList = append(primeList,currentPrime)
currentPrime = 2
if(isprime(n)){
primeList <- append(primeList, n)
return (primeList)
}
}
else{
#cat(sprintf("the number %f is NOT divisible by %f\n", n, currentPrime))
#cat(sprintf("current prime before is: %f\n", currentPrime))
print(c("current prime before:", currentPrime))
currentPrime = nextprime(currentPrime)
#cat(sprintf("current prime after is: %f\n", currentPrime))
print(c("current prime after:", currentPrime))
}
}
}
The problem is that nextprime(currentPrime) doesn't return a base R numeric value. It returns a value with class bigz. Look at the output of cat(nextprime(2).
To fix your code change the line
currentPrime = nextprime(currentPrime)
to
currentPrime = as.numeric(nextprime(currentPrime))

Resources