How to factorize a number in Julia? - 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).

Related

How many zero total in 100 factorial

I have a homework that count total zero in n factorial. What should i do?
I only find way to count trailing of factorial
static int findTrailingZeros(int n)
{
// Initialize result
int count = 0;
// Keep dividing n by powers
// of 5 and update count
for (int i = 5; n / i >= 1; i *= 5)
count += n / i;
return count;
}
The total number of zeros in n! is given by sequence A027869 in the On-line Encyclopedia of Integer Sequences. There really seems to be no way to compute the total number of zeros in n! short of computing n! and counting the number of zeros. With a big int library, this is easy enough. A simple Python example:
import math
def zeros(n): return str(math.factorial(n)).count('0')
So, for example, zeros(100) evaluates to 30. For larger n you might want to skip the relatively expensive conversion to a string and get the 0-count arithmetically by repeatedly dividing by 10.
As you have noted, it is far easier to compute the number of trailing zeros. Your code, in Python, is essentially:
def trailing_zeros(n):
count = 0
p = 5
while p <= n:
count += n//p
p *= 5
return count
As a heuristic way to estimate the total number of zeros, you can first count the number of trailing zeros, subtract that from the number of digits in n!, subtract an additional 2 from this difference (since neither the first digit of n! nor the final digit before the trailing zeros are candidate positions for non-trailing zeros) and guess that 1/10 of these digits will in fact be zeros. You can use Stirling's formula to estimate the number of digits in n!:
def num_digits(n):
#uses Striling's formula to estimate the number of digits in n!
#this formula, known as, Kamenetsky's formula, gives the exact count below 5*10^7
if n == 0:
return 1
else:
return math.ceil(math.log10(2*math.pi*n)/2 + n *(math.log10(n/math.e)))
Hence:
def est_zeros(n):
#first compute the number of candidate postions for non-trailing zerpos:
internal_digits = max(0,num_digits(n) - trailing_zeros(n) - 2)
return trailing_zeros(n) + internal_digits//10
For example est_zeros(100) evaluates to 37, which isn't very good, but then there is no reason to think that this estimation is any better than asymptotic (though proving that it is asymptotically correct would be very difficult, I don't actually know if it is). For larger numbers it seems to give reasonable results. For example zeros(10000) == 5803 and est_zeros == 5814.
How about this then.
count = 0
s = str(fact)
for i in s:
if i=="0":
count +=1
print(count)
100! is a big number:
100! = 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
To be more precise it need ~525 bit and can not be computed without some form of bigint math.
However trailing zeros might be computable on normal integers:
The idea is to limit the result to still fit into your data type. So after each iteration test if the result is divisible by 10. If it is increment your zeros counter and divide the result by 10 while you can. The same goes for any primes except those that divide 10 so not: 2,5 (but without incrementing your zeros counter). This way you will have small sub-result and count of trailing zeros.
So if you do a 2,5 factorization of all the multiplicants in n! the min of the both exponents of 2,5 will be the number of trailing zeros as each pair produces one zero digit (2*5 = 10). If you realize that exponent of 5 is always smaller or equal than exponent of 2 its enough to do the factorization of 5 (just like you do in your updated code).
int fact_trailing_zeros(int n)
{
int i,n5;
for (n5=0,i=5;n>=i;i*=5) n5+=n/i;
return n5;
}
With results:
Trailing zeors of n!
10! : 2
100! : 24
1000! : 249
10000! : 2499
100000! : 24999
1000000! : 249998
10000000! : 2499999
100000000! : 24999999
[ 0.937 ms]
However 100! contains also non trailing zeros and to compute those I see no other way than compute the real thing on a bigint math ... but that does not mean there is no workaround like for trailing zeros...
If it helps here are computed factorials up to 128! so you can check your results:
Fast exact bigint factorial
In case n is bounded to small enough value you can use LUT holding all the factorials up to the limit as strings or BCD and just count the zeros from there... or even have just the final results as a LUT ...
Here some bad code, but it works. You have to use TrailingZeros() only
public static int TrailingZeros(int n)
{
var fac = Factorial(n);
var num = SplitNumber(fac);
Array.Reverse(num);
int i = 0;
int res = 0;
while (num[i] == 0)
{
if (num[i] == 0)
{
res++;
}
i++;
}
return res;
}
public static BigInteger Factorial(int number)
{
BigInteger factorial = 1; // значение факториала
for (int i = 2; i <= number; i++)
{
factorial = factorial * i;
}
return factorial;
}
public static int[] SplitNumber(BigInteger number)
{
var result = new int[0];
int count = 0;
while (number > 0)
{
Array.Resize(ref result, count + 1);
result[count] = (int)(number % 10);
number = number / 10;
count++;
}
Array.Reverse(result);
return result;
}

Dividing two integers, giving the integer quotient and remainder without dividing or multiplying in R

inspired by these posts:
stackoverflow post 1, stackoverflow post 2, geeksforgeeks post
I wanted to write an algorithm in R to divide two integers, giving the integer quotient and remainder without dividing or multiplying.
However, I am struggling to translate the code to R. Here is what I got so far:
Division_alternative <- function(dividend, divisor) {
# Calculate sign of divisor
if (dividend < 0 | divisor < 0) {
sign <- -1
} else {
sign <- 1
}
# Transform to positive
dividend = abs(dividend)
divisor = abs(divisor)
# Initialize the quotient
quotient = 0
while (dividend >= divisor) {
print(sign*quotient)
dividend - divisor
quotient + 1 }
}
a = 25
b = 4
print(Division_alternative(a, b))
I am not sure what is wrong with the code thus far, that it wouldn't return anything. Anyone a clue?
Using proper assignment and making our function return something, we get:
Division_alternative <- function(dividend, divisor) {
##Handle only positive cases
stopifnot((dividend > 0 && divisor >0))
quotient = 0
while (dividend >= divisor) {
# print(sign*quotient)
dividend <- dividend - divisor
quotient <- quotient + 1 }
return(list(dividend, quotient))
}
a = 25
b = 4
print(Division_alternative(a, b))
I am only handling the positive cases since it is the easiest case. I'll let you figure the logic on how to make it work in the other 3 cases since that's a) the fun in doing those things, b) I am not a CS major and never implemented a modulus and remainder function from scratch.

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)

Sorting with parity in julia

Suppose I have the following array:
[6,3,3,5,6],
Is there an already implemented way to sort the array and that returns also the number of permutations that it had to make the algorithm to sort it?
For instance, I have to move 3 times to the right with the 6 so it can be ordered, which would give me parity -1.
The general problem would be to order an arbitrary array (all integers, with repeated indexes!), and to know the parity performed by the algorithm to order the array.
a=[6,3,3,5,6]
sortperm(a) - [ 1:size(a)[1] ]
Results in
3-element Array{Int64,1}:
1
1
1
-3
0
sortperm shows you where each n-th index should go into. We're using 1:size(a)[1] to compare the earlier index to its original indexation.
If your array is small, you can compute the determinant of the permutation matrix
function permutation_sign_1(p)
n = length(p)
A = zeros(n,n)
for i in 1:n
A[i,p[i]] = 1
end
det(A)
end
In general, you can decompose the permutation as a product of cycles,
count the number of even cycles, and return its parity.
function permutation_sign_2(p)
n = length(p)
not_seen = Set{Int}(1:n)
seen = Set{Int}()
cycles = Array{Int,1}[]
while ! isempty(not_seen)
cycle = Int[]
x = pop!( not_seen )
while ! in(x, seen)
push!( cycle, x )
push!( seen, x )
x = p[x]
pop!( not_seen, x, 0 )
end
push!( cycles, cycle )
end
cycle_lengths = map( length, cycles )
even_cycles = filter( i -> i % 2 == 0, cycle_lengths )
length( even_cycles ) % 2 == 0 ? 1 : -1
end
The parity of a permutation can also be obtained from the
number of inversions.
It can be computed by slightly modifying the merge sort algorithm.
Since it is also used to compute Kendall's tau (check less(corkendall)),
there is already an implementation.
using StatsBase
function permutation_sign_3(p)
x = copy(p)
number_of_inversions = StatsBase.swaps!(x)
number_of_inversions % 2 == 0 ? +1 : -1
end
On your example, those three functions give the same result:
x = [6,3,3,5,6]
p = sortperm(x)
permutation_sign_1( p )
permutation_sign_2( p )
permutation_sign_3( p ) # -1

Python Programming While Loop

Hi I'm new to python and programming in general. I am trying write a program that uses a while loop to add integers from 1 to the number entered. the program also has to give an error statement if the user enters a 0 or negative number. So far the integers add up and the error statement works but the program is not looping, it only asks the user to input a number one time. Please help. This is my source code so far. Thanks
x = int(input("Enter a positive number not including zero:" ))
total = 0
n = 1
while n <= x:
total = total + n
n = n + 1
# prints the total of integers up to number entered
print("Sum of integers from 1 to number entered= ",total)
if x <= 0 or x == -x:
print ("invalid entry")
Try this code...
op='y'
while op=='y':
x = int(input("Enter a positive number not including zero:" ))
total = 0
n = 1
if x > 0:
while n <= x:
total = total + n
n = n + 1
# prints the total of integers up to number entered
print("Sum of integers from 1 to number entered= ",total)
else:
print ("invalid entry")
op = raw_input("Are you want to continue this operation (y/n):" )
Put your whole code this way
done = False
while not done:
//your entire code here except the last 2 lines
if x > 0:
done = True

Resources