I have defined a function that takes in a number and returns true if it is a
power of 2. Otherwise, return false:
def is_power_of_two?(num)
n = 0
res = false
if num % 2 == 0
while 2^n <= num
if 2^n == num
res = true
end
n += 1
end
end
puts(n.to_s)
return res
end
# These are tests to check that your code is working. After writing
# your solution, they should all print true.
puts('is_power_of_two?(1) == true: ' + (is_power_of_two?(1) == true).to_s)
puts('is_power_of_two?(16) == true: ' + (is_power_of_two?(16) == true).to_s)
puts('is_power_of_two?(64) == true: ' + (is_power_of_two?(64) == true).to_s)
puts('is_power_of_two?(78) == false: ' + (is_power_of_two?(78) == false).to_s)
puts('is_power_of_two?(0) == false: ' + (is_power_of_two?(0) == false).to_s)
However, my test results turn out to fail four out of five:
0
is_power_of_two?(1) == true: false
16
is_power_of_two?(16) == true: false
64
is_power_of_two?(64) == true: false
77
is_power_of_two?(78) == false: false
0
is_power_of_two?(0) == false: true
The result printed out seems to match what's expected, however, the tests still failed. Does anyone know why this happened?
if you expecting ^ to calculate the power then that is wrong ^ is XOR to calculate power use **
2^2 # 0
2**2 # 4
You always want to check if it is true that it is a power of two, this way it returns false when it is not a power of two.
This feels like a homework question so I'm not going to give you the exact answer, but this should nudge you in the correct direction.
As mohamed-ibrahm says, you're using the wrong operator.
The caret is a bitwise XOR operation. So 2^3 == 1 (because decimal 2 is 010 in binary and decimal 3 is 011 in binary and as all bits are the same except the last, the result is 001 or decimal 1).
Exponentiation is done by double asterisks, so 2**3 == 8
Here's a description of the various operators.
http://www.tutorialspoint.com/ruby/ruby_operators.htm
Related
I'm writing a small program in lua and I was hoping to get some pointers on what would be the most correct way to approach this. Basically, if my number is bigger than the last 200 numbers, return 1, else return 0.
I figure the best way would be a loop?
Let's say x is the position of my number in a table, and then I want to check that it's bigger than the previous 200 numbers and return 1 at the end if it is and 0 if it's not.
while (x > x-a)
do
isbigger = 1;
a = a+1;
return isbigger;
end
I'm not sure if that's correct syntax wise, it also would technically return 1 everytime it goes through the loop and I just want it at the end if true that my number is bigger than the 200 previous one. Also, how do get out of the loop if its false (I'd guess with a break)?
Thanks for any help and have a nice day!
If you are looping over an array of values, you should use a for loop. you also do not want to return isbigger from inside the loop as it will prematurely end the loop
local last = 10
local myNumber = 123
local numbers = {}
--Setup our example numbers table
math.randomseed(os.clock())
for i = 1, 40 do
numbers[i] = math.random(1,200)
end
--Run comparison on our the last x values
local isBigger = true
for i = #numbers, #numbers - last, -1 do
print(myNumber, numbers[i], myNumber > numbers[i])
isBigger= isBigger and myNumber > numbers[i]
end
print("isBigger is: " .. isBigger)
return isBigger and 1 or 0
Example Output
123 181 false
123 6 true
123 77 true
123 78 true
123 145 false
123 130 false
123 104 true
123 114 true
123 6 true
123 4 true
123 15 true
isBigger is: false
The for loop above is better for understanding what is happening, but this one is better for use as it will exit once it has found an result that shows myNumber is not bigger.
local isBigger = true
for i = #numbers, #numbers - last, -1 do
print(myNumber, numbers[i], myNumber > numbers[i])
if not (myNumber > numbers[i]) then
isBigger = false
break
end
end
I have what I believe is a proper implementation of the miller-rabin algorithm using Lua, and I am trying to get a consistent return for prime numbers. It seems my implementation only works half of the time. Although if I try implementing similar code within python, that code works 100% of the time. Could someone point me in the right direction?
--decompose n-1 as (2^s)*d
local function decompose(negOne)
exponent, remainder = 0, negOne
while (remainder%2) == 0 do
exponent = exponent+1
remainder = remainder/2
end
assert((2^exponent)*remainder == negOne and ((remainder%2) == 1), "Error setting up s and d value")
return exponent, remainder
end
local function isNotWitness(n, possibleWitness, exponent, remainder)
witness = (possibleWitness^remainder)%n
if (witness == 1) or (witness == n-1) then
return false
end
for _=0, exponent do
witness = (witness^2)%n
if witness == (n-1) then
return false
end
end
return true
end
--using miller-rabin primality testing
--n the integer to be tested, k the accuracy of the test
local function isProbablyPrime(n, accuracy)
if n <= 3 then
return n == 2 or n == 3
end
if (n%2) == 0 then
return false
end
exponent, remainder = decompose(n-1)
--checks if it is composite
for i=0, accuracy do
math.randomseed(os.time())
witness = math.random(2, n - 2)
if isNotWitness(n, witness, exponent, remainder) then
return false
end
end
--probably prime
return true
end
if isProbablyPrime(31, 30) then
print("prime")
else
print("nope")
end
Python has arbitrary length integers. Lua doesn't.
The problem is in witness = (possibleWitness^remainder)%n.
Lua is unable to calculate exact result of 29^15 % 31 directly.
There is a workaround working for numbers n < sqrt(2^53):
witness = mulmod(possibleWitness, remainder, n)
where
local function mulmod(a, e, m)
local result = 1
while e > 0 do
if e % 2 == 1 then
result = result * a % m
e = e - 1
end
e = e / 2
a = a * a % m
end
return result
end
I'm trying to calculate the sum of the prime numbers in a given number. For instance, for the number 123456, the result will be 10 because 2+3+5 = 10.
I tried to write a code that does that in Lua but I had some issues.
First, here is the code:
function isPrime(num)
if(num == 1 or (num ~= 2 and num%2 == 0)) then
return false
end
for i=3, math.sqrt(num), 2 do
if(num%i == 0) then
return false
end
end
return true
end
function sumOfPrimes(num)
local sum = 0
for digit in string.gmatch(num,"%d") do
local prime = isPrime(digit)
if(isPrime(digit)) then
sum = sum + digit
end
print(digit)
end
return sum
end
function main()
print(sumOfPrimes(123456))
end
main()
It returnes 9 instead of 10. Another thing I've noticed is it adds 1 also to sum, but 1 isn't a prime. What's the problem here?
string.gmatch returns a string, you need to convert it to number before doing calculations
Btw, you are doing the prime validation twice on your loop.
This is a fixed version (returns 10 as expected):
...
function sumOfPrimes(num)
local sum = 0
for digit in string.gmatch(num, "%d") do
digit = tonumber(digit) --needed conversion
local prime_digit = isPrime(digit)
if prime_digit then
sum = sum + digit
end
end
return sum
end
Here is my Lua code for taking user input, and checking if the number entered is prime. My issue is that the program thinks that any even number is not prime, and any odd number is.
print("Enter a number.")
local number = io.read("*n")
function prime(n)
for i = 2, n^(1/2) do
if (n % i) == 0 then
return false
end
return true
end
end
if prime(number) == true then
print("Your number is prime!")
end
if prime(number) == false then
print("Your number is not prime!")
end
Move return true out of the loop.
Hence:
function prime(n)
for i = 2, n^(1/2) do
if (n % i) == 0 then
return false
end
end
return true
end
You return true too soon. You return true as soon as any i meets the condition. You must place the return after the loop.
I know it's an old post but since it's near the top on google I figured it can't hurt to post up my prime finder. It basically does a few simple checks of the obvious stuff and then loops through whats left in a similar fashion to the first example in Jon Ericson' post. Haven't benchmarked it but it seems to cope well enough.
--returns true if prime
function isPrime(n)
local n = tonumber(n)
--catch nil, 0, 1, negative and non int numbers
if not n or n<2 or (n % 1 ~=0) then
return false
--catch even number above 2
elseif n>2 and (n % 2 == 0) then
return false
--primes over 5 end in 1,3,7 or 9
--catch numbers that end in 5 or 0 (multiples of 5)
elseif n>5 and (n % 5 ==0) then
return false
--now check for prime
else
--only do the odds
for i = 3, math.sqrt(n), 2 do
--did it divide evenly
if (n % i == 0) then
return false
end
end
--can defeat optimus
return true
end
end
If you are going to be checking primality, you might as well pick an efficient algorithm. As one answer (cryptically) pointed out, all even numbers greater than 2 are not prime. Therefore, you can short-circuit the check for half the numbers, which doubles the speed to check any particular number:
function check_prime (x)
-- Negative numbers, 0 and 1 are not prime.
if x < 2 then
return false
end
-- Primality for even numbers is easy.
if x == 2 then
return 2
end
if x%2 == 0 then
return false
end
-- Since we have already considered the even numbers,
-- see if the odd numbers are factors.
for i = 3, math.sqrt(x), 2 do
if x%i == 0 then
return false
end
end
return x
end
There are all sorts of optimizations we could apply, but let's take a shot at doing this in a more Lua manner:
function sieve (x)
if x < 2 then
return false
end
-- Assume all numbers are prime until proven not-prime.
local prime = {}
prime[1] = false
for i = 2, x do
prime[i] = true
end
-- For each prime we find, mark all multiples as not-prime.
for i = 2, math.sqrt(x) do
if prime[i] then
for j = i*i, x, i do
prime[j] = false
end
end
end
return prime
end
To use the sieve function:
prime = sieve(number)
if prime[number] then
print("Your number is prime!")
else
print("Your number is not prime!")
end
In my tests, the sieve version is about 6 times faster than the previous algorithm for generating all the primes less than 1 million. (Your mileage may vary.) You can easily check the primality of all numbers less than number at no extra cost. On the other hand, it uses more memory and if you really want check the primality of just one number, it's less efficient.
I would check for primes by dividing the number with 2 and checking if the floor of the division is equal to the division. It looks like this.
if (input/2 == math.floor(input/2)) then
print("is prime")
else
print("is not prime")
end
I was under the impression that = is an assignment, == is a numeric comparison, and === is a symbolic comparison (as well as in some other languages == being equal to and === being identical to. However, looking at the following it would appear that this is not necessarily the case...
In: x == x
Out: True
In: x === x
Out: True
In: 5 == 5
Out: True
In: 5 === 5
Out: True
In: x = 5
Out: 5
In: 5 == x
Out: True
In: 5 === x
Out: True
In: 5 5 == 5x
Out: True
In: 5 5 === 5x
Out: True
In: x == y
Out: x == y
In: x === y
Out: False
In: y = x
Out: 5
In: x == y
Out: True
In: x === y
Out: True
So what exactly is the difference between == and === in Mathematica? I have been looking at the documentation but I still don't quite understand it.
One important difference is that === always returns True or False. == can return unevaluated (which is why it's useful for representing equations.)
In[7]:= y == x^2 + 1
Out[7]= y == 1 + x^2
In[8]:= y === x^2 + 1
Out[8]= False
There are some interesting cases where == returns unevaluated that are worth being aware of while programming. For example:
In[10]:= {} == 1
Out[10]= {} == 1
which can affect things like If[foo=={}, <true>, <false>].
== and === are very similar in the sense that it returns True if the lhs and rhs are equal. One example where they differ is when you compare numbers in different representation formats.
In: 5.==5
Out: True
In: 5.===5
Out: False
Although they are the same numerically, (which is why == returns True), they aren't exactly identical.
FYI, they are different functions internally. == is Equal, whereas === is SameQ.
Equal refers to semantic equality whereas SameQ is syntactic equality. For instance, Sin[x]^2+Cos[x]^2 and 1 are the same number, so they are equal semantically. Since this can not be determined without more transformations, Equal returns unevaluated. However, actual expressions are different, so SameQ gives False.
Sin[x]^2 + Cos[x]^2 == 1
Sin[x]^2 + Cos[x]^2 === 1
Simplify[Sin[x]^2 + Cos[x]^2 == 1]
Note that there's special handling of Real numbers, SameQ[a,b] can return True if a and b differ in the last binary digit. To do more restrictive identity testing, use Order[a,b]==0
a = 1. + 2^-52;
b = 1.;
a === b
Order[a, b]==0
SameQ can return True for expressions that are syntactically different because expression heads may sort arguments automatically. You can prevent automatic sorting by using holding attributes. For instance
c + d === d + c
SetAttributes[SameQ, HoldAll]
c + d === d + c
lhs===rhs yields True if the
expression lhs is identical to rhs,
and yields False otherwise.
and
lhs==rhs returns True if lhs and rhs
are identical.
Reference from here and here.
I direct you to section 2.5: Equality checks of an excellent book by Leonid Shifrin.