Get result from modulo operation in ios swift [duplicate] - ios

How does modulo of negative numbers work in swift ?
When i did (-1 % 3) it is giving -1 but the remainder is 2. What is the catch in it?

The Swift remainder operator % computes the remainder of
the integer division:
a % b = a - (a/b) * b
where / is the truncating integer division. In your case
(-1) % 3 = (-1) - ((-1)/3) * 3 = (-1) - 0 * 3 = -1
So the remainder has always the same sign as the dividend (unless
the remainder is zero).
This is the same definition as required e.g. in the C99 standard,
see for example
Does either ANSI C or ISO C specify what -5 % 10 should be?. See also
Wikipedia: Modulo operation for an overview
how this is handled in different programming languages.
A "true" modulus function could be defined in Swift like this:
func mod(_ a: Int, _ n: Int) -> Int {
precondition(n > 0, "modulus must be positive")
let r = a % n
return r >= 0 ? r : r + n
}
print(mod(-1, 3)) // 2

From the Language Guide - Basic Operators:
Remainder Operator
The remainder operator (a % b) works out how many multiples of b
will fit inside a and returns the value that is left over (known as
the remainder).
The remainder operator (%) is also known as a modulo operator in
other languages. However, its behavior in Swift for negative numbers
means that it is, strictly speaking, a remainder rather than a modulo
operation.
...
The same method is applied when calculating the remainder for a
negative value of a:
-9 % 4 // equals -1
Inserting -9 and 4 into the equation yields:
-9 = (4 x -2) + -1
giving a remainder value of -1.
In your case, no 3 will fit in 1, and the remainder is 1 (same with -1 -> remainder is -1).

If what you are really after is capturing a number between 0 and b, try using this:
infix operator %%
extension Int {
static func %% (_ left: Int, _ right: Int) -> Int {
if left >= 0 { return left % right }
if left >= -right { return (left+right) }
return ((left % right)+right)%right
}
}
print(-1 %% 3) //prints 2
This will work for all value of a, unlike the the previous answer while will only work if a > -b.
I prefer the %% operator over just overloading %, as it will be very clear that you are not doing a true mod function.
The reason for the if statements, instead of just using the final return line, is for speed, as a mod function requires a division, and divisions are more costly that a conditional.

An answer inspired by cdeerinck, which sacrifices speed for simplicity, is this:
infix operator %%
extension Int {
static func %% (_ left: Int, _ right: Int) -> Int {
let mod = left % right
return mod >= 0 ? mod : mod + right
}
}
I tested it with this little loop in a playground:
for test in [6, 5, 4, 0, -1, -2, -100, -101] {
print(test, "%% 5", test %% 5)
}

Related

Dafny 3 maximum int constant

I there in Dafny 3 a maximum/minimum int constant? something like int.MaxValue?
I need it to write a Dafny program that calculates the minimum value in a sequence.
In Dafny, the type int is meant to model mathematical integers. There is no maximum or minimum int constant.
If you want to work with a range of integers, you can define it using a newtype declaration. The Dafny library also contains some standard definitions such as 32 bits integers.
As for finding the minimum int in a sequence, you could do something along these lines:
datatype Option<T> =
| Some(value: T)
| None
function FindMinRec(s: seq<int>, lb: int): int {
if |s| == 0 then lb
else if s[0] < lb
then FindMinRec(s[1..],s[0])
else FindMinRec(s[1..],lb)
}
function FindMin(s: seq<int>): Option<int> {
if |s| == 0 then None else Some(FindMinRec(s[1..],s[0]))
}

the operation % in Dart return a strange value% work in Dart

The var c return 3 but 10/7=1.4285, the rest is 0.4285, operator % has a bug?
void main() {
var a = 10;
var b = 7;
var c;
c = a % b;
print(c);
}
From the documentation of the % operator on num in Dart:
Euclidean modulo operator.
Returns the remainder of the Euclidean division. The Euclidean division of two integers a and b yields two integers q and r such that a == b * q + r and 0 <= r < b.abs().
The Euclidean division is only defined for integers, but can be easily extended to work with doubles. In that case r may have a non-integer value, but it still verifies 0 <= r < |b|.
The sign of the returned value r is always positive.
See remainder for the remainder of the truncating division.
https://api.dart.dev/stable/2.8.4/dart-core/num/operator_modulo.html
The '%' operator returns the remainder left after dividing two numbers. It does not return the decimal part. For example:
10 / 7
1
______
7 ) 10
- 7
______
3
So it returns 3 which is what remains after dividing 10 by 7 without any decimals.
10 / 7 = 1 3/7
What you want to do can be accomplished like this:
var floatNumber = 12.5523;
var x = floatNumber - floatNumber.truncate();

Get RandomPlusMinus in Swift

I want to get a random number either + or -:
But what's wrong here
func randomPlusMinus(value:Float) -> Float {
return value * (arc4random() % 2 ? 1 : -1)
}
Error: Could not find an overload for '*' that accepts the supplied arguments
Try:
func randomPlusMinus(value:Float) -> Float {
let invert: Bool = arc4random_uniform(2) == 1
return value * (invert ? -1.0 : 1.0)
}
I don't think you can say if 0 or if 1. You should be using a boolean value with if and the ternary operator (cond ? v1 : v2).
Then there's the Swift numerics thing (which is really annoying, they need to add/implement more convertible protocols in the Std library :/ )
PS - I don't have an interpreter handy, but I will double check later
Having an explicit test for the result of the modulo operation works for me:
func randomPlusMinus(value:Float) -> Float {
return 0 == (arc4random() % 2) ? value : -value
}
I'm a little late to answering this, but I feel the simplest solution would be:
func randomPlusMinus(value:Float) -> Float {
return value * (arc4random_uniform(2) * 2 - 1)
}
The arc4random call will (supposedly) return 0 50% of the time and 1 50% of the time. So multiplying by 2 gives 0 or 2, then subtracting 1 gives -1 or 1. So the function returns value * -1 50% of the time and value * 1 the other 50% of the time.
I think this is what you are after if you want to random the +- of original value:
func randomPlusMinus(value:Float) -> Float {
let x = arc4random_uniform(2)
switch x {
case 0 :
return value * -1
default :
return value
}
}

product of string

I need a function which return the product of numbers in the string:
SomeFunc("1234") -> 1 * 2 * 3 * 4 = 24
Here is my code:
lists:foldr(fun(X, Y) -> X * Y end, 1, "1234").
But I get 6497400.
Why and how can I fix the code?
Your code is multiplying the ascii codes of the characters, i.e. 49*50*51*52. In order to get your desired result, use
lists:foldr(fun(X, Y) -> (X-$0)*Y end, 1, "1234")
where $0 is the ASCII code for the character '0'.

How can I do mod without a mod operator?

This scripting language doesn't have a % or Mod(). I do have a Fix() that chops off the decimal part of a number. I only need positive results, so don't get too robust.
Will
// mod = a % b
c = Fix(a / b)
mod = a - b * c
do? I'm assuming you can at least divide here. All bets are off on negative numbers.
a mod n = a - (n * Fix(a/n))
For posterity, BrightScript now has a modulo operator, it looks like this:
c = a mod b
If someone arrives later, here are some more actual algorithms (with errors...read carefully)
https://eprint.iacr.org/2014/755.pdf
There are actually two main kind of reduction formulae: Barett and Montgomery. The paper from eprint repeat both in different versions (algorithms 1-3) and give an "improved" version in algorithm 4.
Overview
I give now an overview of the 4. algorithm:
1.) Compute "A*B" and Store the whole product in "C" that C and the modulus $p$ is the input for that algorithm.
2.) Compute the bit-length of $p$, say: the function "Width(p)" returns exactly that value.
3.) Split the input $C$ into N "blocks" of size "Width(p)" and store each in G. Start in G[0] = lsb(p) and end in G[N-1] = msb(p). (The description is really faulty of the paper)
4.) Start the while loop:
Set N=N-1 (to reach the last element)
precompute $b:=2^{Width(p)} \bmod p$
while N>0 do:
T = G[N]
for(i=0; i<Width(p); i++) do: //Note: that counter doesn't matter, it limits the loop)
T = T << 1 //leftshift by 1 bit
while is_set( bit( T, Width(p) ) ) do // (N+1)-th bit of T is 1
unset( bit( T, Width(p) ) ) // unset the (N+1)-th bit of T (==0)
T += b
endwhile
endfor
G[N-1] += T
while is_set( bit( G[N-1], Width(p) ) ) do
unset( bit( G[N-1], Width(p) ) )
G[N-1] += b
endwhile
N -= 1
endwhile
That does alot. Not we only need to recursivly reduce G[0]:
while G[0] > p do
G[0] -= p
endwhile
return G[0]// = C mod p
The other three algorithms are well defined, but this lacks some information or present it really wrong. But it works for any size ;)
What language is it?
A basic algorithm might be:
hold the modulo in a variable (modulo);
hold the target number in a variable (target);
initialize modulus variable;
while (target > 0) {
if (target > modulo) {
target -= modulo;
}
else if(target < modulo) {
modulus = target;
break;
}
}
This may not work for you performance-wise, but:
while (num >= mod_limit)
num = num - mod_limit
In javascript:
function modulo(num1, num2) {
if (num2 === 0 || isNaN(num1) || isNaN(num2)) {
return NaN;
}
if (num1 === 0) {
return 0;
}
var remainderIsPositive = num1 >= 0;
num1 = Math.abs(num1);
num2 = Math.abs(num2);
while (num1 >= num2) {
num1 -= num2
}
return remainderIsPositive ? num1 : 0 - num1;
}

Resources