Related
R gurus,
I would like to write a function to apply dynamic prices based on quantities purchased.
Here is the dataset.
prices <- data.frame(from = c(0,101,201,301,401,501,601,701,801,901,1001,1101,2001),
to = c(100,200,300,400,500,600,700,800,900,1000,1100,2000,10000),
price = c(50,45,40,35,30,25,20,15,10,8,7,6,5))
purchases <- data.frame(customer = LETTERS[1:20],
quantity = c(305,100,70,576,687,1200,5007,491,870,320,80,295,680,1100,1305,1024,1800,7400,3500,730),
bill = NA)
purchases dataset has quantities and price dataset has sliding scale prices for different quantity ranges.
For example, customer A purchased 305 units. To calculate billing for this quantity, first hundred units will be billed at $50, second hundred units at $45, third hundred units at $40 and remaining 5 units at $35. Mathematically:
purchases$bill[1] = 100*50 + 100*45 + 100*40 + 5*35
OR
purchases$bill[1] = 100*prices$price[1] + 100*prices$price[2] + 100*prices$price[3] + 5*prices$price[4]
I wonder what is the best way to do this using an R function to calculate bill for each purchase.
Any help is much appreciated.
Using base R we dan do something like below:
c(prices$price%*%diff(replace(A<-outer(c(0,prices$to),purchases$quantity,"-"),A>0,0)))
[1] 13675 5000 3500 21900 24240 29100 48935 19730 26700 14200 4000 13300 24100 28500 29730 27968
[17] 32700 60900 41400 24950
Elaboration:
price=prices$price
lowr=c(0,prices$to)
qnty=purchases$quantity
x=outer(lowr,qnty,"-")
M=diff(replace(x,x>0,0))
colSums(price*M)##similar to c(price%*%M)
transform(purchases,bill=colSums(price*M))
transform(purchases,bill=colSums(price*M))
customer quantity bill
1 A 305 13675
2 B 100 5000
3 C 70 3500
4 D 576 21900
5 E 687 24240
6 F 1200 29100
7 G 5007 48935
8 H 491 19730
9 I 870 26700
10 J 320 14200
11 K 80 4000
12 L 295 13300
13 M 680 24100
14 N 1100 28500
15 O 1305 29730
16 P 1024 27968
17 Q 1800 32700
18 R 7400 60900
19 S 3500 41400
20 T 730 24950
Here is an example of a bad solution. It is not 100% accurate either.
library(dplyr)
prices <- data.frame(from = c(0,101,201,301,401,501,601,701,801,901,1001,1101,2001),
to = c(100,200,300,400,500,600,700,800,900,1000,1100,2000,10000),
price = c(50,45,40,35,30,25,20,15,10,8,7,6,5))
purchases <- data.frame(customer = LETTERS[1:20],
quantity = c(305,100,70,576,687,1200,5007,491,870,320,80,295,680,1100,1305,1024,1800,7400,3500,800),
bill = NA)
prices$qty = prices$to - prices$from + 1
prices$qty[1] = prices$to[1]
prices$c_qty = cumsum(prices$qty)
prices$bill = prices$qty * prices$price
prices$c_bill = cumsum(prices$bill)
prices$id = 1:nrow(prices)
calculate_billing <- function(qty) {
if(qty <= 100){ price_case = 1}
if(qty >= 101 & qty <= 200) { price_case = 2}
if(qty >= 201 & qty <= 300) { price_case = 3}
if(qty >= 301 & qty <= 400) { price_case = 4}
if(qty >= 401 & qty <= 500) { price_case = 5}
if(qty >= 501 & qty <= 600) { price_case = 6}
if(qty >= 601 & qty <= 700) { price_case = 7}
if(qty >= 701 & qty <= 800) { price_case = 8}
if(qty >= 801 & qty <= 900) { price_case = 9}
if(qty >= 901 & qty <= 1000) { price_case = 10}
if(qty >= 1001 & qty <= 1100) { price_case = 11}
if(qty >= 1101 & qty <= 2000) { price_case = 12}
if(qty >= 2001 & qty <= 10000){ price_case = 13}
if(price_case==1) {
billing = prices$price[price_case]*qty
}
if(price_case>1 & price_case<=11 ) {
remainder <- qty%%100
billing = prices$c_bill[price_case-1] + prices$price[price_case]*remainder
}
if(price_case==12) {
remainder <- qty - 1100
billing = prices$c_bill[price_case-1] + prices$price[price_case]*remainder
}
if(price_case==13) {
remainder <- qty - 2000
billing = prices$c_bill[price_case-1] + prices$price[price_case]*remainder
}
return(billing)
}
purchases %>%
rowwise() %>%
mutate(bill = calculate_billing(quantity))
I really really really can't understand how 15hex converted in Binary form gives me 10101bin.
That should be easy but I can't get it 😰
0x15 == 1*16 + 5*1 == 21
21 == 1*16 + 0*8 + 1*4 + + 0*2 + 1*1 == 10101 (binary)
What's not to love?
Well it's simple. In decimal base, number 15 means
10 + 5, because the number 1 means 1 * 10, and number 5 means 5 * 1.
And in hex, number 15 means:
1 * 16 + 5 * 1, meaning its 21. 21 in binary is 10101.
How to convert hex to binary
Convert each hex digit to 4 binary digits according to this table:
Hex Binary
0 0000
1 0001
2 0010
3 0011
4 0100
5 0101
6 0110
7 0111
8 1000
9 1001
A 1010
B 1011
C 1100
D 1101
E 1110
F 1111
Example #1
Convert (4E)16 to binary:
(4)16 = (0100)2
(E)16 = (1110)2
So
(4E)16 = (01001110)2
Example #2
Convert(4A01)16 to binary:
(4)16 = (0100)2
(A)16 = (1010)2
(0)16 = (0000)2
(1)16 = (0001)2
So
(4A01)16 = (0100101000000001)2
I am solving an example problem, RSA algorithm
I have been given two prime numbers 7 and 11. Let's say p=7 and q=11
I have to calculate the decryption key, d, for some encryption key, e.
Firstly I calculated n=p*q which implies that n=77.
Suppose that e=13,
to calculate d I used the formula d*e = 1 mod fi,
where fi=(p-1)(q-1), and so fi=60
The final equation becomes 13*d = 1 mod fi
According to some solved example
d is calculated to be 37, how is this result obtained?
Any help would be appreciated.
i think this is what you are looking for
Verifying the answer is easy, finding it in the first place, a little more work.
Verification:
13 * 37 = 481
481 = 8 * 60 + 1
Hence if you divide 13 * 37 by 60 you have remainder 1.
Alternate answers:
Any integer of the form (37 + 60 k) where k is any integer is also a solution. (97, -23, etc.)
To find the solution you can proceed as follows:
Solve:
13 d = 1 + 60 k
mod 13:
0 = 1 + 8k (mod 13)
8k = -1 (mod 13)
Add 13's until a multiple of 8 is found:
8k = 12 or 25 or 38 or 51 or 64 .... aha a multiple of 8!
k = 64 / 8 = 8
Substitute k = 8 back into 13 d = 1 + 60 k
13 d = 1 + 8 * 60 = 481
481 /13 = 37
and that is the answer.
Use the extended Euclidean algorithm to compute integers x and y such that
13*x+60*y=1
Then x is the answer you're looking for, mod 60.
I would like to convert a 4-dimensional array into a 2-dimensional data set. I present code for two approaches that do that: one approach using a brute force method involving cbind and rbind and a second approach using nested for-loops. Nevertheless, I am thinking there is likely a better way. Thank you for any suggestions.
R <- 3 # regions
M <- 5 # sites
J <- 2 # samples
T <- 4 # years
# 4-dim example array
y <- array(NA, dim = c(M, J, T, R))
# region 1
y[,1,1,1] = 1; y[,2,1,1] = 2;
y[,1,2,1] = 3; y[,2,2,1] = 4;
y[,1,3,1] = 5; y[,2,3,1] = 6;
y[,1,4,1] = 7; y[,2,4,1] = 8;
# region 2
y[,1,1,2] = 9; y[,2,1,2] = 10;
y[,1,2,2] = 11; y[,2,2,2] = 12;
y[,1,3,2] = 13; y[,2,3,2] = 14;
y[,1,4,2] = 15; y[,2,4,2] = 16;
# region 3
y[,1,1,3] = 17; y[,2,1,3] = 18;
y[,1,2,3] = 19; y[,2,2,3] = 20;
y[,1,3,3] = 21; y[,2,3,3] = 22;
y[,1,4,3] = 23; y[,2,4,3] = 24;
# desired two-dimensional data set
z = read.table(text = "
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8
9 10 11 12 13 14 15 16
9 10 11 12 13 14 15 16
9 10 11 12 13 14 15 16
9 10 11 12 13 14 15 16
9 10 11 12 13 14 15 16
17 18 19 20 21 22 23 24
17 18 19 20 21 22 23 24
17 18 19 20 21 22 23 24
17 18 19 20 21 22 23 24
17 18 19 20 21 22 23 24
", sep = "", header = FALSE)
# using cbind and rbind to convert 4-dimensional array to 2-dimensional data set
r1 <- cbind(y[,,1,1], y[,,2,1], y[,,3,1], y[,,4,1])
r2 <- cbind(y[,,1,2], y[,,2,2], y[,,3,2], y[,,4,2])
r3 <- cbind(y[,,1,3], y[,,2,3], y[,,3,3], y[,,4,3])
my.data <- rbind(r1,r2,r3)
my.data
# using nested for-loops to convert 4-dimensional array to 2-dimensional data set
m2 <- matrix(NA, nrow = M*R, ncol= J*T)
for(i in 1:R) {
for(j in 1:T) {
m2[(M*(i-1) + (1:M)), (J*(j-1) + (1:J))] = y[,,j,i]
}
}
m2
# basis for nested for-loops above
m3 <- matrix(NA, nrow = M*R, ncol= J*T)
m3[(M*0 + (1:M)), (J*0 + (1:J))] = y[,,1,1]
m3[(M*0 + (1:M)), (J*1 + (1:J))] = y[,,2,1]
m3[(M*0 + (1:M)), (J*2 + (1:J))] = y[,,3,1]
m3[(M*0 + (1:M)), (J*3 + (1:J))] = y[,,4,1]
m3[(M*1 + (1:M)), (J*0 + (1:J))] = y[,,1,2]
m3[(M*1 + (1:M)), (J*1 + (1:J))] = y[,,2,2]
m3[(M*1 + (1:M)), (J*2 + (1:J))] = y[,,3,2]
m3[(M*1 + (1:M)), (J*3 + (1:J))] = y[,,4,2]
m3[(M*2 + (1:M)), (J*0 + (1:J))] = y[,,1,3]
m3[(M*2 + (1:M)), (J*1 + (1:J))] = y[,,2,3]
m3[(M*2 + (1:M)), (J*2 + (1:J))] = y[,,3,3]
m3[(M*2 + (1:M)), (J*3 + (1:J))] = y[,,4,3]
m3
It took a couple of tries, but:
matrix(aperm(y,c(1,4,2,3)),15)
or more generally
matrix(aperm(y,c(1,4,2,3)),prod(dim(y)[c(1,4)]))
In case someone comes here looking for a similar question about collapsing to an array, but to one that is greater than dimension=2, use array() instead of matrix(), with the dim() argument to specify what dimensions you want. Code that will also work for the problem above is:
array(aperm(y,c(1,4,2,3)), dim=c(15,8))
This can easily be modified if you wanted the output to be, say, a 3d array by putting in an additional value to dim(). The aperm() bit may not be necessary for your particular case, but you should always check that the collapsed array is in the order you want and use aperm() accordingly.
How to calculate modulus of 5^55 modulus 221 without much use of calculator?
I guess there are some simple principles in number theory in cryptography to calculate such things.
Okay, so you want to calculate a^b mod m. First we'll take a naive approach and then see how we can refine it.
First, reduce a mod m. That means, find a number a1 so that 0 <= a1 < m and a = a1 mod m. Then repeatedly in a loop multiply by a1 and reduce again mod m. Thus, in pseudocode:
a1 = a reduced mod m
p = 1
for(int i = 1; i <= b; i++) {
p *= a1
p = p reduced mod m
}
By doing this, we avoid numbers larger than m^2. This is the key. The reason we avoid numbers larger than m^2 is because at every step 0 <= p < m and 0 <= a1 < m.
As an example, let's compute 5^55 mod 221. First, 5 is already reduced mod 221.
1 * 5 = 5 mod 221
5 * 5 = 25 mod 221
25 * 5 = 125 mod 221
125 * 5 = 183 mod 221
183 * 5 = 31 mod 221
31 * 5 = 155 mod 221
155 * 5 = 112 mod 221
112 * 5 = 118 mod 221
118 * 5 = 148 mod 221
148 * 5 = 77 mod 221
77 * 5 = 164 mod 221
164 * 5 = 157 mod 221
157 * 5 = 122 mod 221
122 * 5 = 168 mod 221
168 * 5 = 177 mod 221
177 * 5 = 1 mod 221
1 * 5 = 5 mod 221
5 * 5 = 25 mod 221
25 * 5 = 125 mod 221
125 * 5 = 183 mod 221
183 * 5 = 31 mod 221
31 * 5 = 155 mod 221
155 * 5 = 112 mod 221
112 * 5 = 118 mod 221
118 * 5 = 148 mod 221
148 * 5 = 77 mod 221
77 * 5 = 164 mod 221
164 * 5 = 157 mod 221
157 * 5 = 122 mod 221
122 * 5 = 168 mod 221
168 * 5 = 177 mod 221
177 * 5 = 1 mod 221
1 * 5 = 5 mod 221
5 * 5 = 25 mod 221
25 * 5 = 125 mod 221
125 * 5 = 183 mod 221
183 * 5 = 31 mod 221
31 * 5 = 155 mod 221
155 * 5 = 112 mod 221
112 * 5 = 118 mod 221
118 * 5 = 148 mod 221
148 * 5 = 77 mod 221
77 * 5 = 164 mod 221
164 * 5 = 157 mod 221
157 * 5 = 122 mod 221
122 * 5 = 168 mod 221
168 * 5 = 177 mod 221
177 * 5 = 1 mod 221
1 * 5 = 5 mod 221
5 * 5 = 25 mod 221
25 * 5 = 125 mod 221
125 * 5 = 183 mod 221
183 * 5 = 31 mod 221
31 * 5 = 155 mod 221
155 * 5 = 112 mod 221
Therefore, 5^55 = 112 mod 221.
Now, we can improve this by using exponentiation by squaring; this is the famous trick wherein we reduce exponentiation to requiring only log b multiplications instead of b. Note that with the algorithm that I described above, the exponentiation by squaring improvement, you end up with the right-to-left binary method.
a1 = a reduced mod m
p = 1
while (b > 0) {
if (b is odd) {
p *= a1
p = p reduced mod m
}
b /= 2
a1 = (a1 * a1) reduced mod m
}
Thus, since 55 = 110111 in binary
1 * (5^1 mod 221) = 5 mod 221
5 * (5^2 mod 221) = 125 mod 221
125 * (5^4 mod 221) = 112 mod 221
112 * (5^16 mod 221) = 112 mod 221
112 * (5^32 mod 221) = 112 mod 221
Therefore the answer is 5^55 = 112 mod 221. The reason this works is because
55 = 1 + 2 + 4 + 16 + 32
so that
5^55 = 5^(1 + 2 + 4 + 16 + 32) mod 221
= 5^1 * 5^2 * 5^4 * 5^16 * 5^32 mod 221
= 5 * 25 * 183 * 1 * 1 mod 221
= 22875 mod 221
= 112 mod 221
In the step where we calculate 5^1 mod 221, 5^2 mod 221, etc. we note that 5^(2^k) = 5^(2^(k-1)) * 5^(2^(k-1)) because 2^k = 2^(k-1) + 2^(k-1) so that we can first compute 5^1 and reduce mod 221, then square this and reduce mod 221 to obtain 5^2 mod 221, etc.
The above algorithm formalizes this idea.
To add to Jason's answer:
You can speed the process up (which might be helpful for very large exponents) using the binary expansion of the exponent. First calculate 5, 5^2, 5^4, 5^8 mod 221 - you do this by repeated squaring:
5^1 = 5(mod 221)
5^2 = 5^2 (mod 221) = 25(mod 221)
5^4 = (5^2)^2 = 25^2(mod 221) = 625 (mod 221) = 183(mod221)
5^8 = (5^4)^2 = 183^2(mod 221) = 33489 (mod 221) = 118(mod 221)
5^16 = (5^8)^2 = 118^2(mod 221) = 13924 (mod 221) = 1(mod 221)
5^32 = (5^16)^2 = 1^2(mod 221) = 1(mod 221)
Now we can write
55 = 1 + 2 + 4 + 16 + 32
so 5^55 = 5^1 * 5^2 * 5^4 * 5^16 * 5^32
= 5 * 25 * 625 * 1 * 1 (mod 221)
= 125 * 625 (mod 221)
= 125 * 183 (mod 183) - because 625 = 183 (mod 221)
= 22875 ( mod 221)
= 112 (mod 221)
You can see how for very large exponents this will be much faster (I believe it's log as opposed to linear in b, but not certain.)
/* The algorithm is from the book "Discrete Mathematics and Its
Applications 5th Edition" by Kenneth H. Rosen.
(base^exp)%mod
*/
int modular(int base, unsigned int exp, unsigned int mod)
{
int x = 1;
int power = base % mod;
for (int i = 0; i < sizeof(int) * 8; i++) {
int least_sig_bit = 0x00000001 & (exp >> i);
if (least_sig_bit)
x = (x * power) % mod;
power = (power * power) % mod;
}
return x;
}
5^55 mod221
= ( 5^10 * 5^10 * 5^10 * 5^10 * 5^10 * 5^5) mod221
= ( ( 5^10) mod221 * 5^10 * 5^10 * 5^10 * 5^10 * 5^5) mod221
= ( 77 * 5^10 * 5^10 * 5^10 * 5^10 * 5^5) mod221
= ( ( 77 * 5^10) mod221 * 5^10 * 5^10 * 5^10 * 5^5) mod221
= ( 183 * 5^10 * 5^10 * 5^10 * 5^5) mod221
= ( ( 183 * 5^10) mod221 * 5^10 * 5^10 * 5^5) mod221
= ( 168 * 5^10 * 5^10 * 5^5) mod221
= ( ( 168 * 5^10) mod 221 * 5^10 * 5^5) mod221
= ( 118 * 5^10 * 5^5) mod221
= ( ( 118 * 5^10) mod 221 * 5^5) mod221
= ( 25 * 5^5) mod221
= 112
What you're looking for is modular exponentiation, specifically modular binary exponentiation. This wikipedia link has pseudocode.
Chinese Remainder Theorem comes to mind as an initial point as 221 = 13 * 17. So, break this down into 2 parts that get combined in the end, one for mod 13 and one for mod 17. Second, I believe there is some proof of a^(p-1) = 1 mod p for all non zero a which also helps reduce your problem as 5^55 becomes 5^3 for the mod 13 case as 13*4=52. If you look under the subject of "Finite Fields" you may find some good results on how to solve this.
EDIT: The reason I mention the factors is that this creates a way to factor zero into non-zero elements as if you tried something like 13^2 * 17^4 mod 221, the answer is zero since 13*17=221. A lot of large numbers aren't going to be prime, though there are ways to find large primes as they are used a lot in cryptography and other areas within Mathematics.
This is part of code I made for IBAN validation. Feel free to use.
static void Main(string[] args)
{
int modulo = 97;
string input = Reverse("100020778788920323232343433");
int result = 0;
int lastRowValue = 1;
for (int i = 0; i < input.Length; i++)
{
// Calculating the modulus of a large number Wikipedia http://en.wikipedia.org/wiki/International_Bank_Account_Number
if (i > 0)
{
lastRowValue = ModuloByDigits(lastRowValue, modulo);
}
result += lastRowValue * int.Parse(input[i].ToString());
}
result = result % modulo;
Console.WriteLine(string.Format("Result: {0}", result));
}
public static int ModuloByDigits(int previousValue, int modulo)
{
// Calculating the modulus of a large number Wikipedia http://en.wikipedia.org/wiki/International_Bank_Account_Number
return ((previousValue * 10) % modulo);
}
public static string Reverse(string input)
{
char[] arr = input.ToCharArray();
Array.Reverse(arr);
return new string(arr);
}
Jason's answer in Java (note i < exp).
private static void testModulus() {
int bse = 5, exp = 55, mod = 221;
int a1 = bse % mod;
int p = 1;
System.out.println("1. " + (p % mod) + " * " + bse + " = " + (p % mod) * bse + " mod " + mod);
for (int i = 1; i < exp; i++) {
p *= a1;
System.out.println((i + 1) + ". " + (p % mod) + " * " + bse + " = " + ((p % mod) * bse) % mod + " mod " + mod);
p = (p % mod);
}
}
Just provide another implementation of Jason's answer by C.
After discussing with my classmates, based on Jason's explanation, I like the recursive version more if you don't care about the performance very much:
For example:
#include<stdio.h>
int mypow( int base, int pow, int mod ){
if( pow == 0 ) return 1;
if( pow % 2 == 0 ){
int tmp = mypow( base, pow >> 1, mod );
return tmp * tmp % mod;
}
else{
return base * mypow( base, pow - 1, mod ) % mod;
}
}
int main(){
printf("%d", mypow(5,55,221));
return 0;
}
This is called modular exponentiation(https://en.wikipedia.org/wiki/Modular_exponentiation).
Let's assume you have the following expression:
19 ^ 3 mod 7
Instead of powering 19 directly you can do the following:
(((19 mod 7) * 19) mod 7) * 19) mod 7
But this can take also a long time due to a lot of sequential multipliations and so you can multiply on squared values:
x mod N -> x ^ 2 mod N -> x ^ 4 mod -> ... x ^ 2 |log y| mod N
Modular exponentiation algorithm makes assumptions that:
x ^ y == (x ^ |y/2|) ^ 2 if y is even
x ^ y == x * ((x ^ |y/2|) ^ 2) if y is odd
And so recursive modular exponentiation algorithm will look like this in java:
/**
* Modular exponentiation algorithm
* #param x Assumption: x >= 0
* #param y Assumption: y >= 0
* #param N Assumption: N > 0
* #return x ^ y mod N
*/
public static long modExp(long x, long y, long N) {
if(y == 0)
return 1 % N;
long z = modExp(x, Math.abs(y/2), N);
if(y % 2 == 0)
return (long) ((Math.pow(z, 2)) % N);
return (long) ((x * Math.pow(z, 2)) % N);
}
Special thanks to #chux for found mistake with incorrect return value in case of y and 0 comparison.