I'm trying to solve the FizzBuzz game.
I need to check if a number is divisible by 3. So, when we take a number and divide it by 3, we need that operation to have NO REST, or 0 REST.
The solution given to me is this:
def fizzbuzz(number)
if number % 3 == 0
return "Fizz"
end
Why does they propose to use the "%"symbol? Why not the "/"symbol? Or both work as the same?
How should I check if the division has NO REST?
division operator / - gives the quotient of the division whatever the remainder of the division is. So you cannot determine if a number is perfectly divisible (remainder = 0) or not perfectly divisible (with non-zero remainder) using a division operator (/).
10 / 3
#=> 3
modulo operator % - gives the remainder of the division. If perfectly divisible, the output is 0, if not-perfectly divisible the output is non-zero value.
10 % 3
#=> 1
In your case number % 3 == 0 is true only if number is divisible by 3 with 0 remainder (i.e if number passed into the method frizzbuzz is a multiple of 3 like -12, -3, 3, 6, 9, etc )
Ruby has 4 division operators.
divmod returns the division and the remainder
number = 15
number.divmod(7) # => 2, 1
modulo alias % returns the remainder only
number = 15
number % 7 # => 1
number.modulo(7) # => 1
div alias / returns the integer division if both operands are integers, and floating-point division if either operand is a float.
number = 15
number / 7 # => 2
number.div(7) # => 2
1.0 * number / 7 # => 2.142857142857143
fdiv always returns a full precision floating-point division
number = 15
number.fdiv(7) # => 2.142857142857143
% is the Modulus - Divides left hand operand by right hand operand and returns remainder. \ is just the Divider. No Rest means that x % y == 0.
lets take an example to understand better:
number1 = 12
number2 = 13
lets see if number1 and number2 is devisible by 4 ok?
number1 / 4 = 3 and the rest = 0
number2 / 4 = 3 and the rest = 1
so the "/" operation let us know the result of devision operation
and the "%" operation let us know the rest of devision operation
so if we take our examples the number1 is devisible by 3 because
number1 % 3 = 0 ( the rest )
Related
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();
I am making a Pong game in Delphi.
Paddle.Left := X - Paddle.Width div 2;
Paddle.Top := ClientHeight - Paddle.Height - 2;
I expect the output of 5/2 to be 2.5, but the actual output is 2.
The div operator performs integer division (5 div 2 = 2, throwing away the decimal .5), whereas the / operator performs floating point division (5 / 2 = 2.5).
In VCL, a control's Left, Top, Width, and Height values are expressed using whole integers, not floating point numbers.
In FMX, a control's Position and Size values are expressed using floating point numbers.
div is the integer division operator. It is a binary operator that takes two integers, and returns an integer, the truncated value of the division. For instance,
0 div 3 = 0
1 div 3 = 0
2 div 3 = 0
3 div 3 = 1
4 div 3 = 1
5 div 3 = 1
6 div 3 = 2
...
If you want to perform a floating-point division, you need to use the / operator:
0 / 3 = 0
1 / 3 = 0.33333333333333
2 / 3 = 0.66666666666666
3 / 3 = 1
4 / 3 = 1.33333333333333
5 / 3 = 1.66666666666666
6 / 3 = 2
...
Of course, the result cannot be stored in an integer variable. If you eventually need an integer value to specify a pixel on the screen, you need to round the floating-point value to an integer (using the Round function).
I have one program downloaded from internet and need to get each digit printed out from a three digit number. For example:
Input: 123
Expected Output:
1
2
3
I have 598
Need to Get:
5
9
8
I try using this formula but the problem is when number is with decimal function failed:
FIRST_DIGIT = (number mod 1000) / 100
SECOND_DIGIT = (number mod 100) / 10
THIRD_DIGIT = (number mod 10)
Where number is the above example so here is calulation:
FIRST_DIGIT = (598 mod 1000) / 100 = 5,98 <== FAILED...i need to get 5 but my program shows 0 because i have decimal point
SECOND_DIGIT = (598 mod 100) / 10 = 9,8 <== FAILED...i need to get 9 but my program shows 0 because i have decimal point
THIRD_DIGIT = (598 mod 10) = 8 <== CORRECT...i get from program output number 8 and this digit is correct.
So my question is is there sample or more efficient code that get each digit from number without decimal point? I don't want to use round to round nearest number because sometime it fill failed if number is larger that .5.
Thanks
The simplest solution is to use integer division (\) instead of floating point division (/).
If you replace each one of your examples with the backslash (\) instead of forward slash (/) they will return integer values.
FIRST_DIGIT = (598 mod 1000) \ 100 = 5
SECOND_DIGIT = (598 mod 100) \ 10 = 9
THIRD_DIGIT = (598 mod 10) = 8
You don't have to do any fancy integer calculations as long as you pull it apart from a string:
INPUT X
X$ = STR$(X)
FOR Z = 1 TO LEN(X$)
PRINT MID$(X$, Z, 1)
NEXT
Then, for example, you could act upon each string element:
INPUT X
X$ = STR$(X)
FOR Z = 1 TO LEN(X$)
Q = VAL(MID$(X$, Z, 1))
N = N + 1
PRINT "Digit"; N; " equals"; Q
NEXT
Additionally, you could tear apart the string character by character:
INPUT X
X$ = STR$(X)
FOR Z = 1 TO LEN(X$)
SELECT CASE MID$(X$, Z, 1)
CASE " ", ".", "+", "-", "E", "D"
' special char
CASE ELSE
Q = VAL(MID$(X$, Z, 1))
N = N + 1
PRINT "Digit"; N; " equals"; Q
END SELECT
NEXT
I'm no expert in Basic but looks like you have to convert floating point number to Integer. A quick google search told me that you have to use Int(floating_point_number) to convert float to integer.
So
Int((number mod 100)/ 10)
should probably the one you are looking for.
And, finally, all string elements could be parsed:
INPUT X
X$ = STR$(X)
PRINT X$
FOR Z = 1 TO LEN(X$)
SELECT CASE MID$(X$, Z, 1)
CASE " "
' nul
CASE "E", "D"
Exponent = -1
CASE "."
Decimal = -1
CASE "+"
UnaryPlus = -1
CASE "-"
UnaryNegative = -1
CASE ELSE
Q = VAL(MID$(X$, Z, 1))
N = N + 1
PRINT "Digit"; N; " equals"; Q
END SELECT
NEXT
IF Exponent THEN PRINT "There was an exponent."
IF Decimal THEN PRINT "There was a decimal."
IF UnaryPlus THEN PRINT "There was a plus sign."
IF UnaryNegative THEN PRINT "There was a negative sign."
I'm looking for a rails function that could return the number to the nearest power of ten(10,100,1000), and also need to support number between 0 and 1 (0.1, 0.01, 0.001):
round(9) = 10
round(19) = 10
round(79) = 100
round(812.12) = 1000
round(0.0321) = 0.01
round(0.0921) = 0.1
I've looking on : Round number down to nearest power of ten
the accepted answer using the length of the string, that can't applied to number between 0 and 1.
updated
Round up to nearest power of 10 this one seems great. But I still can't make it work in rails.
I'm not sure about any function which automatically rounds the number to the nearest power of ten. You can achieve it by running the following code:
def rounded_to_nearest_power_of_ten(value)
abs_value = value.abs
power_of_ten = Math.log10(abs_value)
upper_limit = power_of_ten.ceil
lower_limit = power_of_ten.floor
nearest_value = (10**upper_limit - abs_value).abs > (10**lower_limit - abs_value).abs ? 10**lower_limit : 10**upper_limit
value > 0 ? nearest_value : -1*nearest_value
end
Hope this helps.
Let's simplify your problem to the following form - let the input numbers be in the range [0.1, 1), how would rounding of such numbers look like then?
The answer would be simple - for numbers smaller than 0.5 we would return the number 0.1, for larger numbers it would be 1.0.
All we have to do is to make sure that our number will be in that range. We will "move" decimal separator and remember how many moves we made in second variable. This operation is called normalization.
def normalize(fraction)
exponent = 0
while fraction < (1.0/10.0)
fraction *= 10.0
exponent -= 1
end
while fraction >= 1.0
fraction /= 10.0
exponent += 1
end
[fraction, exponent]
end
Using above code you can represent any floating number as a pair of normalized fraction and exponent in base 10. To recreate original number we will move decimal point in opposite direction using formula
original = normalized * base^{exponent}
With data property normalized we can use it in our simple rounding method like that:
def round(number)
fraction, exponent = normalize(number)
if fraction < 0.5
0.1 * 10 ** exponent
else
1.0 * 10 ** exponent
end
end
if the number is >= 1.0, this should work.
10 ** (num.floor.to_s.size - ( num.floor.to_s[0].to_i > 4 ? 0 : 1))
Try this:
def round_tenth(a)
if a.to_f >= 1
return 10 ** (a.floor.to_s.size - ( a.floor.to_s[0].to_i > 4 ? 0 : 1))
end
#a = 0.0392
c = a.to_s[2..a.to_s.length]
b = 0
c.split('').each_with_index do |s, i|
if s.to_i != 0
b = i + 1
break
end
end
arr = Array.new(100, 0)
if c[b-1].to_i > 4
b -= 1
if b == 0
return 1
end
end
arr[b-1] = 1
return ("0." + arr.join()).to_f
end
class Numeric
def name
def helper x, y, z
num = self.abs
r = 1
while true
result = nil
if num.between?(x, y)
if num >= y/2.0
result = y.round(r+1)
else
result = x.round(r)
end
return self.negative? ? -result : result
end
x *= z; y *= z; r += 1
end
end
if self.abs < 1
helper 0.1, 1, 0.1
else
helper 1, 10, 10
end
end
end
Example
-0.049.name # => -0.01
12.name # => 10
and so on, you are welcome!
i have this code in if statement , and i think it is very big , how can i change this by short code and for infinity i.e that i want the if statement to work on two and after two by sixteen i.e 2 += 16 , forever , i know that my question might be not understandable
but please help me
Take the current count and subtract 2. If the number is divisible by 16 (the remainder when you do modulo division is zero), then your statement is true.
if ((count - 2) % 16 == 0)
{
_secondBall.hidden = YES;
}
This can be reduced to a mathematical problem. What you want is to divide by 16 and see if there is no 'remainder'. The 'modulo' operator gives you this remainder. You can Google it if you want to understand. So, as others have quickly posted before me, modulo in Objective-C is done via %. So x % 16 means: divide x by 16 and return the remainder (or: subtract 16 from x until x is smaller than 16). x % 16 will be a number between 0 and 15. Always. When x % 16 is 0, it means x is dividable by 16.
Since you want to take action when count is 2 + 16 * n, you want to subtract 2 from count first. Like so if ( ( count - 2 ) % 16 == 0). Or you can do this, which is shorter but perhaps less easy to understand: if ( count % 16 == 2 ).
Try this:
if ((count - 2) % 16 == 0)
Use this syntax
if ((count-2) % 16 == 0)