Why is modulus defined the way it is in programming languages - math

I'm not asking about the definition but rather why the language creators chose to define modulus with asymmetric behavior in C++. (I think Java too)
Suppose I want to find the least number greater than or equal to n that is divisible by f.
If n is positive, then I do:
if(n % f)
ans = n + f - n % f;
If n is negative:
ans = n - n % f;
Clearly, this definition is not the most expedient when dealing with negative and positive numbers. So why was it defined like this? In what case does it yield expediency?

Because it's using "modulo 2 arithmetic", where each binary digit is treated independently of the other. Look at the example on "division" here

You're mistaken. When n is negative, C++ allows the result of the modulus operator to be either negative or positive as long as the results from % and / are consistent, so for any given a and b, the expression (a/b)*b + a%b will always yield a. C99 requires that the result of a % b will have the same sign as a. Some other languages (e.g., Python) require that the sign of a % b have the same sign as b.
This means the expression you've given for negative n is not actually required to work in C++. When/if n%f yields a positive number (even though n is negative), it will give ans that's less than n.

Related

Smallest perfect square divisible by all elements of an array (with large numbers)

Given an array A[] with n elements, the task is to find S mod (10^9+7), in which S is the smallest perfect square which is divisible by all the elements A[i] (1<=i<=n) of the given array.
So, the problem is very easy if the value of A[i] and n is small. But in this case, I don't know what to do when A[i] can up to 10^7 and n can up to 10^5. So everybody help me pls!
The smallest integer X which is a multiple of all the A_i is called the least common multiple of the A_i. It's also true that every common multiple of the A_i is divisible by X. So S is divisible by X, or equivalently S is a multiple of X.
The LCM can computed fairly efficiently by the algorithms mentioned in the wikipedia article, but remember our final goal is S, a perfect square, not X. Also, the size of X (and S) is likely to be enormous given the constraints in your problem.
Thus I think the correct approach is to use a modified Sieve of Eratosthenes (or just obtain from some online source a list of primes up to 3163) to completely factor all the A_i simultaneously into their prime power factorizations. Since the A_i < 107 you need only include primes <= 103.5. Now, with each A_i factored into its prime power factorization use the prime factorization method to find the LCM, but still retain this in prime power format, in other words don't yet multiply everything together. Next, scan through each of the powers and add 1 to any odd powers. Now you have the prime power factorization of S. Iterate through these prime powers, multiplying each one into the product and taking the product mod (109+7) at each step.

Time complexity of this recursive block

int recursiveFunc(int n) {
if (n == 1) return 0;
for (int i = 2; i < n; i++)
if (n % i == 0) return i + recursiveFunc(n / i);
return n;
}
I know Complexity = length of tree from root node to leaf node * number of leaf nodes, but having hard time to come to an equation.
This one is tricky, because the runtime is highly dependent on what number you provide in as input in a way that most recursive functions are not.
For starters, notice that the way that this recursion works, it takes in a number and then either
returns without making any further calls if the number is prime, or
recursively calls itself on number divided by that proper factor.
This means that in one case, the function, called on a number n, will do Θ(n) work and make no calls (which happens if the number is prime), and in the other case will do Θ(d) work and then make a recursive call on the number n / d, which happens if n is composite and is the largest divisor of n.
One useful fact we'll use to analyze this function is that given a composite number n, the smallest factor d of n is never any greater than √n. If it were, then we would have that n = df for some other factor f, and since d is the smallest proper divisor, we'd have that f ≥ d, so df > √n √ n = n, which would be impossible.
With that in mind, we can argue that the worst-case runtime of this function is O(n), and in fact that happens when n is prime. Here's how to see this. Imagine the worst-case amount of time this function can take if it ends up making a recursive call. In that case, the function will do at most Θ(√n) work (let's assume our smallest divisor is as large as possible), then recursively makes a call on a number whose size is at most n / 2 (which is the absolute largest number we could get as part of the recursive call. In that case, we'd get this recurrence relation under the pessimistic assumption that we do the maximum work possible
T(n) = T(n / 2) + √n
This solves, by the Master Theorem, to Θ(√n), which is less work than what we'd do if we had a prime number as an input.
But what happens if, instead, we do the maximum amount of work possible for some number of iterations, and then end up with a prime number and stop? In that case, using the iteration method, we'd see that the work done would be
n1/2 + n1/4 + ... + n / 2k,
which would happen if we stopped after k iterations. In this case, notice that this expression is maximized when we pick k to be as small as possible - which would correspond to stopping as soon as possible, which happens if we pick a prime number for n.
So in this sense, the worst-case runtime of this function is Θ(n), which happens for n being a prime number, with composite numbers terminating much faster than this.
So how fast can this function be? Well, imagine, for example, that we have a number of the form pk, where p is some prime number. In that case, this function will do Θ(p) work to discover p as a prime factor, then recursively call itself on the number pk-1. If you think about what this will look like, this function will end up doing Θ(p) work Θ(k) times for a total runtime of Θ(pk). And since n = pk, we'd have k = logp n, so the runtime would be Θ(p logp n). That's minimized at either p = 2 or p = 3, and in either case gives us a runtime of Θ(log n) in this case.
I strongly suspect that's the best case here, though I'm not entirely sure. But what this does mean is that
the worst-case runtime is definitely Θ(n), occurring at prime numbers, and
the best-case runtime is O(log n), which I'm fairly certain is a tight bound but I'm not 100% sure how to prove.

Modulo operator in decryption

I'm creating an encryptor/decryptor for ascii strings where I take the ascii value of a char, add 1 to it, then mod it by the highest ascii value so that I get a valid ascii char out.
The problem is the decryption.
Let's say that (a + b) % c = d
I know b, c, and d's values.
How do I get the a variables value out from that?
This is exactly the ROT1 substitution cipher. Subtract 1, and if less than lowest value (0 I assume, given how you're describing it), then add the highest value.
Using terms like "mod," while accurate, make this seem more complicated than it is. It's just addition on a ring. When you go past the last letter, you come back to the first letter and vice-versa. Once you put your head around how the math works, the equations should pop out. Basically, you just add or subtract as normal (add to encrypt, subtract to decrypt in this case), and at the end, mod "normalizes" you back onto the ring of legal values.
Use the inverse formula
a = (b - d) mod c
or in practice
a = (b - d + c) % c.
The term + c needs to be added as a safeguard because the % operator does not implement a true modulo in the negatives.
Let's assume that c is 2, d is 0 and b is 4.
Now we know that a must be 2... Or 4 actually.. or 6... Or any other even number.
You can't solve this problem, there are infinite solutions.

DFA to mathematical notation

Let's say I have a DFA with alphabet {0,1} which basically accepts any strings as long as there is no consecutive 0's (at most one 0 at a time). How do I express this in a mathematical notation?
I was thinking of any number of 1's followed by either one or none 0's, then any number of 1's..... but couldn't figure out the appropriate mathematical notation for it.
My attempt but obviously incorrect since 1010 should be accepted but the notation does not indicate so:
As a regular expression you could write this as 1*(01+)*0?. Arbitrary many ones, then arbitrary many groups of exactly one zero followed by at least one one, and in the end possibly one zero. Nico already wrote as much in a comment. Personally I'd consider such a regular expression sufficiently formal to call it mathematical.
Now if you want to write this using exponents, you could do something like
L = {1a (0 11+bi)c 0d mod 2 | a,bi,c,d ∈ ℕ for 1≤i≤c}
Writing a bit of formula in the exponents has the great benefit that you don't have to split the place where you use the exponent and the place where you define the range. Here all my numbers are natural numbers (including zero). Adding one means at least one repetition. And the modulo 2 makes the exponent 0 or 1 to express the ? in the regular expression.
Of course, there is an implied assumption here, namely that the c serves as a kind of loop, but it doesn't repeat the same expression every time, but the bi changes for each iteration. The range of the i implies this interpretation, but it might be considered confusing or even incorrect nonetheless.
The proper solution here would be using some formal product notation using a big ∏ with a subscript i = 1 and a superscript c. That would indicate that for every i from 1 through c you want to compute the given expression (i.e. 011+bi) and concatenate all the resulting words.
You could also give a recursive definition: The minimal fixpoint of the following definition
L' = {1, 10} ∪ {1a 0 b | a ∈ ℕ, a > 0, b ∈ L'}
is the language of all words which begin with a 1 and satisfy your conditions. From this you can build
L = {ε, 0} ∪ L' ∪ {0 a | a ∈ L'}
so you add the empty word and the lone zero, then take all the words from L' in their unmodified form and in the form with a zero added in front.

How to determine that remaining of dividing number X by number Y is zero using regular expression

i want to know is it possible to validate that deviding two number has remaining zero in result or not?
for example dividing number 4 on number two has zero in remaining.
4/2=0 (this is true)
but 4/3=1 (this is not true)
is there any expression for validation such case?
Better Question :
Is There any validation expression to validate this sentence ?
Remainder is zero
thank you
You can use a Modulo operator. The modulo operation finds the remainder of division of one number by another
y mod x
5 mod 2 =1 (2x2=4, 5-4=1)
9 mod 3 = 0 (3*3=9)
You can think of it, how many times does x fit in y and then take the remainder.
In computing the modulo operator is integrated in most programming languages, along with division, substraction etc. Check modulo and then your language on google (probably its mod).
This is called the modulo function. It essentially gives the remainder of a division of two integer number. So you can test for the modulo funtion returning zero. For example, in Python you would write
if a % b == 0:
# a can be divided by b with zero remainder

Resources