I'm trying to re-order some Excel columns using JExcel. I also need to find references to other cells and then re-map them to reference the correct cells. I feel like I've done a lot of the hard work, but I've hit a stumbling block.
I found this code on wikipedia, as linked to from SO:
public static String toBase26(int number){
number = Math.abs(number);
String converted = "";
// Repeatedly divide the number by 26 and convert the
// remainder into the appropriate letter.
do
{
int remainder = number % 26;
converted = (char)(remainder + 'A') + converted;
number = (number - remainder) / 26;
} while (number > 0);
return converted;
}
But when I run the number 35 into it, this is what happens:
number = 35
remainder = 9
converted= char(9+'A')+"" = J
number = (35-9)/26 = 1
1>0
remainder = 1
char(1+'A') = B
converted= char(1+'A')+"J" = BJ
Which is, in a way expected, as Base 10 (35) = Base 26 (19). But I'm actually wanting to refer to column AJ.
I can't untangle what change I need to make to get the right letters out. Whenever I try to work it out on paper, I end up ruining the previous letters extracted. For instance, I don't think this would work, as it means I end up with remainder as 8, the first time, and then that would be converted into I, unless I've missed something?
Any help on this would be greatly appreciated. I've looked around and wasted enough time on this. I just want some help to get it to work.
The stumbling block behind this 'hexavidecimal system' is that it has a 0, but the units column skips the 0 and ranges only from A-Z. Consider the following conversion from decimal:
A 1 (0*26 + 1)
...
Z 26 (0*26 + 26)
AA 27 (1*26 + 1)
...
AZ 52 (1*26 + 26)
BA 53 (2*26 + 1)
...
BZ 78 (2*26 + 26)
CA 79 (3*26 + 1)
...
ZZ 702 (26*26 + 26)
AAA 703 (1*26*26 + 1*26 + 1)
See the problem? There are missing 'zeroes' in the hexavidecimal numbers:
00A 1
...
00Z 26
0AA 27
...
0AZ 52
0BA 53
...
0BZ 78
0CA 79
...
0ZZ 702 (26*26 + 26)
AAA 703 (1*26*26 + 1*26 + 1)
However, the units column does NOT have the zeroes ever!
Obviously we do not print these zeroes, but it should aid your understanding of what is going wrong.
Here's our algorithm. I wrote the algorithm under the assumption that decimal 0 = hexavidecimal A, 1 -> B, 25 -> Z, 26 -> AA and so on because it makes it easier for me to wrap my head around. If this isn't the assumption you want just subtract 1 before running the code :)
0. If number =< 0, return.
1. Modulo by 26. Convert 0-25 to 'A'-'Z'. //This is our units column.
Loop {
2. Divide the number by 26 (integer division rounding down).
3. If number =< 0, return.
4. Modulo by 26. Convert 0-25 to 'Z','A'-'Y'. //This is our next column (prepend to string output).
}
Example
Converting decimal 730 -> ABC hexavigesimal
Modulo of 730 by 26 = 2 -> 'C' for units column
Divide 730 by 26 = 28
Modulo 28 by 26 = 2 -> 'B' for tens column
Divide 28 by 26 = 1
Modulo 1 by 26 = 1 -> 'A' for hundreds column
Divide 1 by 26 = 0
Number is empty, therefore return 'ABC'
Here is a simple Python function to compute the hexavigesimal representation of a number (in an arbitrary base), where a is equal to 1 (not 0).
The tricky part of the problem is that at each step you're taking between 1 and 10 off the remainder, so you need to account for that in your modulo. The code below accounts for it by subtracting 1 from the number each time. Then 0 becomes a very convenient end condition, because you cannot represent 0 in hexavigesimal (the wikipedia entry denotes it λ).
# Formats a number as a bijective base N string.
def bijective(n, base):
chars = ''
while n != 0:
chars = chr((n - 1) % base + 97) + chars
n = (n - 1) / base
return chars
# Examples!
if __name__ == '__main__':
base = 26
for n in range(1, 2 * base * base):
print('{}: {}'.format(n, bijective(n, base)))
See it in action on pythonanywhere.
I included a javascript version in this gist.
Related
I was working on a programming exercise and was stuck on figuring out the correct algorithm. Here is the problem:
Given a decimal number, how many minimum possible steps are required to convert this to zero provided:
Change the bit i if the next bit i+1 is '1' and all the other bits i+2 and later are 0
Change the last bit without restriction
For example:
if input is (8)Base10 = (1000)Base2, then the steps taken are:
1000→1001→1011→1010→1110→1111→1101→1100→0100→0101→0111→0110→0010→0011→0001→0000
total 15 steps are required.
Complete the following definition:
int minStepsRequired(long number)
It's ok to get a pseudo code or just the algorithm. This is not a homework or assignment.
This is a wonderful problem for a recursive algorithm.
If the length of the binary representation is 0, you can already tell the answer. Or if length 0 is not allowed, then if the length is 1 you tell the answer depending on whether that one bit is 0 or 1.
If the length is longer than 1:
If the first bit is 0, the answer is the same as it would be without that 0 bit. Remove it and call recursively to get the answer.
If the first bit is 1, divide into three subproblems and find the step count for each:
Establish a situation where you are allowed to change the leading 1 to 0. This means it should be followed by a 1 and then all 0s. Write a recursive auxiliary algorithm for this. It is going to be quite similar to the main algorithm, and likely they can share some logic.
Flip the 1 to 0 (1 step)
Convert the remaining bits bits to 0. Another recursive call.
The algorithm may take a long time. It is actually counting the steps, so takes time proportional to the number of steps, which I think is roughly proportional to the input number. Your method takes a long argument, but with my algorithm for large long values it may not terminate witin the lifetime of the computer it is running on. Also the number of steps may overflow an int and even a long (if the input is a negative long value).
The fast way
The following solution doesn’t require recursion and runs in constant time. I can’t explain properly how it works, which is a serious problem if we want to use it for something. I played with some examples, saw a pattern and generalized it. By contrast IMHO some of the beauty of the recursive solution above is that it is straightforward to understand (if you understand recursion).
Example: Input 8 or 1000 binary. Result 15 or 1111 binary. The pattern is: each bit of the result is the XOR of the previous bit of the result and the bit in the same position in the input. So from 1000 just copy the front bit, 1. The following bit is 1 XOR 0 = 1, where 1 is the front bit of the result and 0 is taken from the input. The remaining two bits are calculated the same way.
A longer example so you can check if you understood:
Input: 115 = 1110011
Result: 1011101 = 93
Or in code:
static BigInteger calculateStepsRequired(long number) {
// Take sign bit
int bit = number < 0 ? 1 : 0;
BigInteger result = BigInteger.valueOf(bit);
for (int i = 0; i < 63; i++) {
number = number << 1;
int sign = number < 0 ? 1 : 0;
bit = (bit + sign) % 2;
result = result.shiftLeft(1).add(BigInteger.valueOf(bit));
}
return result;
}
I have checked this method against my own implementation of the first algorithm above using various inputs up to 100 000 000, and they always agree, so I believe that the fast method is correct too. I still suggest that you should code, run and test it to verify that I got it right.
At first, I tried to solve it with a recursive depth-first function (in NodeJS) but it just worked for small numbers - an input value such as 10^5 would generate a runtime error due to the number of recursive calls in the stack.
So then I tried to see how I could reduce the problem to the sum of smaller problems and found out that the number of steps for N, being N a power of 2, was
Rule #1
N * 2 - 1
(e.g.: number of steps for 2 is 3, for 32 is 63, for 256 is 511, and so on).
Then I had find what to do with any other number (that is not a power of 2) and since any integer is the sum of different powers of 2 (hence the binary representation), I only had to see if the number of steps would add up as well ... but it was not the case. However, I did find that I had to not just add the number of steps from every power of two, but to
Rule #2
subtract and add the steps in an alternate fashion, starting from the highest order digit
Demonstration
Given number 42 (101010 in binary)
Let's first apply Rule #1
1 0 1 0 1 0
^ ^ ^ ^ ^ ^
| | | | | |_ 0 steps
| | | | |___ 2*2-1 = 3 steps
| | | |_____ 0 steps
| | |_______ 2*8-1 = 15 steps
| |_________ 0 steps
|___________ 2*32-1 = 63 steps
And secondly, applying Rule #2:
63 - 15 + 3 = 51
The total number of steps is 51
Implementation (JavaScript)
function minOperations(n) {
const bin = n.toString(2);
const digitCount = bin.length;
let accumulator = 0;
let sign = 1;
for (let i = 0; i < digitCount; ++i) {
const digit = Number.parseInt(bin.charAt(i));
const power = digit > 0 ? Math.pow(2, digitCount - (i + 1)) : 0;
const steps = digit * (power * 2 - 1);
accumulator += steps * sign;
sign = sign * (digit == 0 ? 1 : -1);
}
return accumulator;
}
Here is a recursive PHP function for computing the number of steps required. It operates by noting there are two possible requirements:
convert a string to 0s (the overall requirement); and
convert a string to a 1 followed by a string of 0s (to allow flipping the preceding digit)
The second requirement is obviously an extension of the first, and so it's possible to write a recursive function which does both. It has a special case for the single digit length string, just checking if it needs to be flipped or not.
function reduce($bits, $value = '0') {
if (strlen($bits) == 1) {
// a single bit can be flipped as needed
return ($bits[0] == $value) ? 0 : 1;
}
if ($bits[0] == $value) {
// nothing to do with this bit, flip the remainder
return reduce(substr($bits, 1));
}
// need to convert balance of string to 1 followed by 0's
// then we can flip this bit, and then reduce the new string to 0
return reduce(substr($bits, 1), '1') + 1 + reduce(str_pad('1', strlen($bits) - 1, '0'));
}
Demo on 3v4l.org
This function can be adapted to store the actual steps taken, then the number of steps is just the count of that array (-1, since we put the original value in the array too). To store the steps we need to keep track of the first part of the string ($prefix in the below code) as well as the part we are reducing:
function reduce($bits, $prefix, $value = '0') {
if (strlen($bits) == 1) {
// a single bit can be flipped as needed
return array($prefix . ($bits[0] == '0' ? '1' : '0'));
}
if ($bits[0] == $value) {
// nothing to do with this bit, flip the remainder
$prefix .= $bits[0];
return reduce(substr($bits, 1), $prefix);
}
// need to convert balance of string to 1 followed by 0's
$prefix .= $bits[0];
$steps = reduce(substr($bits, 1), $prefix, '1');
// now we can flip this bit
$prefix = substr($prefix, 0, -1) . ($bits[0] == '0' ? '1' : '0');
$steps[] = $prefix . str_pad('1', strlen($bits) - 1, '0');
// now reduce the new string to 0
$steps = array_merge($steps, reduce(str_pad('1', strlen($bits) - 1, '0'), $prefix));
return $steps;
}
You can run this like so:
$bin = decbin($i);
$steps = array_merge(array($bin), reduce($bin, ''));
echo "$i ($bin) takes " . (count($steps) - 1) . " steps\n";
print_r($steps);
Output for an input of 8:
8 (1000) takes 15 steps
Array
(
[0] => 1000
[1] => 1001
[2] => 1011
[3] => 1010
[4] => 1110
[5] => 1111
[6] => 1101
[7] => 1100
[8] => 0100
[9] => 0101
[10] => 0111
[11] => 0110
[12] => 0010
[13] => 0011
[14] => 0001
[15] => 0000
)
Demo on 3v4l.org
Gray code
Looking at the steps we can see that this is actually a Gray code (Reflected Binary Code) counting from the original value down to 0. So if we generate a list of sufficient codes to cover the starting value, we can simply look for the binary representation of the starting value in that list, and that will give us the number of steps required to get back to 0:
function gray_code($bits) {
if ($bits == 1) {
return array('0', '1');
}
else {
$codes = gray_code($bits - 1);
return array_merge(array_map(function ($v) { return '0' . $v; }, $codes),
array_map(function ($v) { return '1' . $v; }, array_reverse($codes))
);
}
}
$value = 8;
$bin = decbin($value);
// get sufficient gray codes to cover the input
$gray_codes = gray_code(strlen($bin));
$codes = array_flip($gray_codes);
echo "$bin takes {$codes[$bin]} steps to reduce to 0\n";
// echo the steps
for ($i = $codes[$bin]; $i >= 0; $i--) {
echo $gray_codes[$i] . PHP_EOL;
}
Demo on 3v4l.org
If you don't need the individual steps you can just use a Gray code to binary converter to find the number of steps. This is super fast:
function gray_to_binary($value) {
$dec = $value;
for ($i = 1; $i < strlen($value); $i++) {
$dec[$i] = (int)$dec[$i-1] ^ (int)$value[$i];
}
return $dec;
}
echo bindec(gray_to_binary(decbin(115)));
Output:
93
Demo on 3v4l.org
A Gray Code Generator
We can use an iterative Gray code generator to count down the steps from our original code. The advantage of this is that it doesn't consume any memory to store the codes so it can work for very large numbers. This version uses a Gray code to binary converter that works with integers rather than strings as did the one above:
function gray_to_binary($value) {
$dec = 0;
$bits = floor(log($value, 2));
for ($i = $bits; $i >= 0; $i--) {
$dec = $dec | (((($dec >> ($i + 1)) ^ ($value >> $i)) & 1) << $i);
}
return $dec;
}
function iterate_gray($value) {
// get the equivalent starting binary value
$code = decbin($value);
yield $code;
$len = strlen($code);
$count = gray_to_binary($value);
while ($count > 0) {
// flip the bit which corresponds to the least significant 1 bit in $count
$xor = 1;
while (($count & $xor) == 0) $xor <<= 1;
$value ^= $xor;
yield sprintf("%0{$len}b", $value);
$count--;
}
}
foreach (iterate_gray(8) as $code) {
echo $code . PHP_EOL;
}
Output:
1000
1001
1011
1010
1110
1111
1101
1100
0100
0101
0111
0110
0010
0011
0001
0000
Demo on 3v4l.org
Here is a PHP implementation of Ole's "fast way" algorithm. The idea is the same:
Initialize the result with the first bit of the number (starting from the left)
For every following bit of the number, XOR it with the previous bit of the result, which gives a new bit for the result
function getBit($number, $i)
{
// Extracts bit i from number
return ($number & (1<<$i)) == 0 ? 0 : 1;
}
function minStepsRequired($number)
{
$i = 30; // Enough to handle all positive 32-bit integers
$bit = getBit($number, $i); // First bit
$res = $bit;
do
{
$i--;
$bit ^= getBit($number, $i); // Computes XOR between previous bit of the result and current bit of the number
$res = ($res<<1) + $bit; // Shifts the result to the left by 1 position and adds the new bit
}
while($i>0);
return $res;
}
var_dump(minStepsRequired(8)); // Outputs 15
var_dump(minStepsRequired(115)); // Outputs 93
It is important to notice that the first k bits, which are zeroes can be left as they are and you only start with the (k + 1)'th bit and we ignore all the starting bits, having a value of zero and always aim to increase their number. This is our primary goal and thus, we always reduce the problem-space to a similar, but smaller problem-space. Now, assuming that your number looks like
1b1b2b3...bn
you need to make sure that b1 is 1 and b2, b3, ..., bn is 0 in order to be able to modify the bit prior to b1 to 0. After that happened, you know that b2 is 1 and all the subsequent bits are 0, then the new goal is to change b2 to 0, knowing that all the subsequent bits are 0.
You can keep track of your progress with a stack which can have as much elements as many bits you are working with, always its top will represent your current goal.
So, when you want to zero your first bit, then achieving the right sequence of subsequent bits represent subtasks for you before you can change your bit and once you succeeded doing so, you need to proceed similarly, but ignoring the first bit. You can number the steps.
Assuming that a number of
1...0000000
can be zeroed in 2^n - 1 steps, the total number of steps to do equals with 2^n - 1 + the number of steps needed to achieve the combination we see above. I didn't check whether it's 2^n - 1 though
private static int reduce(String s) {
int count = 0;
char[] ch = s.toCharArray();
for (int i = ch.length - 1; i >= 0; i--) {
if (i == 0 && ch[i] == '0') {
return count - 1;
}
if (i == 0 && ch[i] == '1') {
return count + 1;
}
if (ch[i] == '0') {
count++;
} else {
count++;
ch[i] = '0';
i++;
}
}
return count;
}
def minOperations(n):
number = []
while n>0:
number.append(n%2)
n = n // 2
ans = 0
sign = 1
for i in range(len(number)):
if number[i] == 1:
ans = (2**(i+1) - 1) - ans
return ans
I am developing a small application where I am given some string "MRUGDQ" and a shift value 3 for example. Then I shift each letter to left by 3 and the result would be "JORDAN". For instance M would be replaced by J and R would be replaced by O and so on.
So now this is the approach I was thinking of using, but I was wondering if this is efficient and can I improve my solution?
Assumptions I make:
I am assuming my string will be either capital A to Z letter or small a to z letter and therefore the ascii range is from 65 to 90 and 97 to 122 respectively.
Pesudo Code
get ascii value of char
(assume char happens to be between the capital letter range)
add the shift value to the char ascii value
if new ascii value <= 90
replace old letter by new letter
else
int diff = new ascii value - 90
while (new ascii value <= 90) {
decrement diff value by 1
increment new ascii value by 1
}
add remaining diff to 65 and set that as new ascii value
replace old letter by new letter
Do that for each letter in the string.
Please let me know if my approach is correct or if I can be more efficient.
I don't see much to improve, except your handling of the new char is out of range.
If you like to "roll" the overlapping amount back to the beginning of your range, than just calculate: (x % 90) + 64(*) (with x being the ascii value after adding the shift value).
Example:
'Y' (89) + 3 = '\' 92
92 % 90 = 2
2 + 64 = 'B' (66)
You need to start from 64, to avoid skipping over 'A', which has the value 65.
(*) The general formula is: (value % upper bound) + (lower bound - 1).
You could also use (value % upper bound + 1) + lower bound.
I need to write a converter in Java where it asks the user for an input, sourceAlphabet and targetAlphabet). The code should then provide an answer which has converted the sourceAlphabet to the targetAlphabet.
Alphabets should be given in the form:
-"0123456789" (Base 10),
-"abcdefghijklmnopqrstuvwxyz" (Alphabet),
-"0123456789ABCDEF" (Hexadecimal), etc.
Each alphabet value is a single unique ASCII character.
These are some sample inputs and answers I am looking for from the code:
convert("129","0123456789","01") === "10000001"
convert("FF","0123456789ABCDEF","0123456789") === "255"
convert("svip","abcdefghijklmnopqrstuvwxyz","0123456789ABCDEF") === "50C23"
Any help in getting me started on this problem would be greatly appreciated.
As a starting point, create a function that converts from decimal to hexadecimal.
The best tools to help you do this will be the modulo operator (x % y) and the division operator (x / y). Modulo (or mod) gives you the remainder, so if you imagine have a number like 24, 24 % 16 = 8, while 24 / 16 = 1. Notice that if I had 31 % 16, I would receive 15.
With those tools, you can operate on the input decimal and repeatedly mod by the base over the number to get the remainder, and then set the decimal equal to itself divided by the base.
For example.
Step 1.
Decimal : 31
String : ""
Base : 16
31 % 16 = 15
31 / 16 = 1
Step 2
Decimal : 1
String : "E"
Base : 16
1 % 16 = 1
1 / 16 = 1
Step 3
Decimal : 0
String :"1E"
Base : 16
Fin
Hope that helps.
I am trying to figure out a function f(x) that would calculate the number of leaves in a k-ary tree. For example, assume we created a tree that began with root 4 with 3 children, each of -1,-2,-3 respectively. Our leaves would only be 0 values, not null values. I have spent the past day trying to figure out a function and it seems like nothing I do goes in the correct direction.
EX:
4
/ | \
3 2 1
/ |\ /| /
2 1 0 1 0 0
/| / /
1 0 0 0
/
0
7 Leaves.
Any help would be very much appreciated! Thanks!
To clarify, I need a mathematical equation that derives the same answer as code would if I recursively transversed the tree.
More examples:
{4,7}{5,13}{6,24}{7,44}{8,81}{9,149}{10,274}{11,504}{12,927}{13,1705}{14,3136}{15,5768}{16,10609}{17,19513}{18,35890}{19,66012}{20,121415}
public int numleaves(TreeNode node) {
if (node == null)
return 0;
else if (node.getLeft() == null && node.getMiddle() == null && node.getRight() == null)
return 1;
else
return numleaves(node.getLeft()) + numleaves(node.getMiddle()) + numleaves(node.getRight());
}
I cannot answer your question, but it has a solution. I can only outline the case for the number of children k being equal to 2. The case k=3 leads to a cubic polynomial with two complex and one real solution, I lack the tools here to derive them in a non-numerical way.
But let's have a look at the case k=2. Interestingly, this problem is very closely related to the Fibonacci numbers, except for having different boundary conditions.
Writing down the recursive formula is easy:
a(n) = a(n-1) + a(n-2)
with boundary conditions a(1)=1 and a(0)=1. The characteristic polynomial of this is
x^2 = x + 1
with the solutions x1 = 1/2 + sqrt(5)/2 and x2 = 1/2 - sqrt(5)/2. It means that
a(n) = u*x1^n + v*x2^n
for some u and v is the explicit formula for the sequence we're looking for. Putting in the boundary conditions we get
u = (sqrt(5)+1)/(2*sqrt(5))
v = (sqrt(5)-1)/(2*sqrt(5))
i.e.
a(n) = (sqrt(5)+1)/(2*sqrt(5))*(1/2 + sqrt(5)/2)^n + (sqrt(5)-1)/(2*sqrt(5))*(1/2 - sqrt(5)/2)^n
for k=2.
Your code seems to be computing a Tribonacci sequence with starting values 1, 1 and 2. This is sequence A000073 from the On-Line Encyclopedia of Integer Sequences, starting from the third entry of that sequence rather than the first. The comments section of the encyclopedia page gives an explicit formula: since this is a linear recurrence relation with a degree 3 characteristic polynomial, there's a closed form solution in terms of the roots of that polynomial. Here's a short piece of Python 2 code based on the given formula that produces the first few values. (See the edit below for a simplification.)
from math import sqrt
c = (1 + (19 - 3 * sqrt(33))**(1/3.) + (19 + 3 * sqrt(33))**(1/3.)) / 3.
m = (1 - c) / 2
p = sqrt(((3*c - 5)*(c+1)/4))
j = 1/((c-m)**2 + p**2)
b = (c - m) / (2 * p*((c - m)**2 + p**2))
k = complex(-j / 2, b)
r1 = complex(m, p)
def f(n):
return int(round(j*c**(n+2) + (2*k*r1**(n+2)).real))
for n in range(0, 21):
print n, f(n)
And the output:
0 1
1 1
2 2
3 4
4 7
5 13
6 24
7 44
8 81
9 149
10 274
11 504
12 927
13 1705
14 3136
15 5768
16 10609
17 19513
18 35890
19 66012
20 121415
EDIT: the above code is needlessly complicated. With the round operation, the second term in f(n) can be omitted (it converges to zero as n increases), and the formula for the first term can be simplified. Here's some simpler code that generates the same output.
s = (19 + 297**0.5)**(1/3.)
c = (1 + s + 4/s)/3
j = 3 - (2 + 1/c)/c
for n in range(0, 32):
print n, int(round(c**n / j))
I can't help it, but I see Binomial tree in it. http://en.wikipedia.org/wiki/Binomial_heap
I think that good approximation could be sum of k-th row of pascal triangle, where k stands for the number of the root node.
Isn't this easier to understand:
We set the starting values for the tribonacci sequence into a list called result. Then we put these values into 3 variables. We change the variable content based on the tribonacci formula (new a is a+b+c, new b is old a, new c is old b). Then we calculate to whatever tribonacci number we want to go up to and store each result into our result list. At the end, we read out the indexed list.
result=[1,1,2]
a,b,c=result[-1],result[-2],result[-3]
for i in range(40):
a,b,c=a+b+c,a,b
result.append(a)
for e,f in enumerate(result):
print e,f
I am new to Java, actually programming in general. I understand that the modulus operator (%) returns the remainder of two numbers, however, I do not understand why 17 % 40 = 17.
I understand that 40 % 17 = 6, and 17 % 5 = 2, and 40 % 5 = 0. I get the gist of what value is returned as the remainder. But 17 % 40 = 17 has me stumped.
The only rationalization I can devise is that since the remainder is less than 1 the total value 17 is returned, why not 0? Please help to explain this enigma to me.
When you divide 17/40, quotient is 0 and the remainder is 17.
The modulo operator (%) returns the remainder.
i.e
a % b = remainder of a / b
Equation from Wiki by Knuth:
a = 17
n = 40
floor(a/n) = 0
so r = 17
When n > a then r is simply a.
i guess learning back the 3rd and 4th standard maths is the key point.
if u see (hope understand the division syntax. its the popular 3rd std way )
____
40)17
you will get a reminder 17 as 17 is not divisible by 40.
then there will be an adition of '.' and then the fraction will be added
If you have the numbers a and b, their quotient q and remainder r, then the following has to be true:
q · b + r = a
That is, if you multiply the quotient (q) by the divisor (b) and add the remainder (r), the result is the dividend (a).
In your case a = 17, b = 40, q = 0 and so r has to be 17.
Note: the equation above is just a rearrangement of the equation from Nikolay Kuznetsov's answer, but I think it's easier to understand this way.
Maybe this is a different and more helpful way to think about it.
When we apply division to integer numbers a and b, we are really trying to relate a and b like this:
a = Q * b + R
a is some multiple of b, plus some leftover. Q and R are integers; to keep this simple, let's also just think of non-negative numbers. The multiple, Q, is the quotient and leftover, R, is the remainder -- the smallest ones that make this relation work.
In most languages, a / b gives you Q, and and a % b gives you R. (In fact processors tend to compute both at once -- these are so related.)
So if a is 17 and b is 40, it only works if you write:
17 = 0 * 40 + 17
This is why a % b must be 17.
(Note that it gets more complex when considering negative numbers.)