Processing 3.3.7 Carmichael function - processing

So I am trying to make a carmichael function in processing for some RSA encryption stuff I am playing with, but the modulo function seems to give many wrong answers.
here is my code:
int carmichael(int n) {
int checkIndex = 0;
int m = 1;
ArrayList<Integer> coprimes = findCoprimesLessThan(n);
println(coprimes);
for(m = 1; m < 50; m++){
for(checkIndex = 0; checkIndex < coprimes.size(); checkIndex++){
int a = coprimes.get(checkIndex);
float mod = pow(a, m) % n;
println(a, m, n, mod, pow(a, m), pow(a, m) % n);
if (mod == 1) {
continue;
}
if (mod != 1){
break;
}
return m;
}
}
return 1;
}
And for an input of say, 31, it loops forever (I have it stop at 100 just for this reason so it just outputs 1 if it goes through all 100 and doesn't find anything) when it should give 30. I believe I have narrowed it down to the modulo operation not working on large numbers as that seems to be the problem, for example:
when a = 3, m = 30, and n = 31, my println statement gives this:
3 30 31 18.0 2.05891136E14 18.0
and all of that is correct except the modulo, it gives 18.0 when it should be 1.0. I am unsure of anyway to get around this as even doing a "manual modulus" like this:
while(mod >= n){
mod-= n;
}
results in the exact same problem. All research I have done into the carmichael function has led me to either confusion or here which was no help.

My guess is you're hitting a limit of float precision.
Float values can only track a certain amount of precision. Try running this example program:
float one = 123456789;
float two = one + 1;
println(one == two);
You would expect this to print false, but if you run it, you'll see that it prints true instead. This is because we're outside the bounds of precision.
To get around this, you could upgrade to the double type. Double values have the same problem, but at a higher level of precision.
double one = 123456789;
double two = one + 1;
println(one == two);
Getting back to your code, by default Processing treats everything as a float value. This is fine for most cases, but if you need lots of precision then you're better off switching to double value.
int a = 3;
int m = 30;
int n = 31;
double p = Math.pow(a, m);
println(p);
double mod = p % n;
println(mod);
Note that I'm using Math.pow() instead of pow(). The Math.pow() function comes from Java and takes and returns double values instead of float values.
(By the way, this is the type of example program I was talking about in the comments.)

Related

Calculation particular row mod 10^9+7 of pascal table

what i want to store is a particular row of pascal table elements mod 10^9+7 in an array i tried to code it but it is failing somewhere when value is huge of like 10^5
here is the code. i have tried to apply modular inverse here and modular arithmetic here mod is 10^9+7
void pascal_row(ll n){
memset(soo,0,MAX);
soo[0] = 1; //First element is always 1
for(ll i=1; i<n/2+1; i++){ //Progress up, until reaching the middle value
soo[i] = ( ( soo[i-1] %mod ) * ((( (n-i+1)%mod * calcInverse(i,mod)%mod) % mod ))%mod)%mod;
}
for(ll i=n/2+1; i<=n; i++){ //Copy the inverse of the first part
soo[i] = soo[n-i]%mod;
}
}
here is what my modular inverse function look
long long calcInverse(long long a, long long n)
{
long long t = 0, newt = 1;
long long r = n, newr = a;
while (newr != 0) {
auto quotient = r /newr;
tie(t, newt) = make_tuple(newt, t- quotient * newt);
tie(r, newr) = make_tuple(newr, r - quotient * newr);
}
if (r > 1)
throw runtime_error("a is not invertible");
if (t < 0)
t += n;
return t;
}
Please tell what is the correct way of doing this Thanks
There's a relationship between the elements of Pascal's triangle and the choose function (where n choose r = n!/(r!*(n-r)!).) Specifically, starting from zero, the n'th row and r'th column of Pascal's triangle is n choose r. To find a particular row, you know what n you want, and then you should iterate over the possible values of r, find n choose r, and then take your modulus.
I'd recommend Java's BigInteger class for this, because it will handle any overflow errors you might be getting.

Effectively calculate function

Given
f(n) = 1+x+x^2+x^3+……+x^n, (n >=0 && n is a integer)
input x, n, how can we work out the result with a greater efficiency?
It's a geometric progression. Noting that
(x-1)f(n) = x^{n+1}-1
you get
f(n)=(x^{n+1}-1)/(x-1).
This does n multiplies and n increments. It's easy to put the sum into closed form, but computing the closed form requires evaluating xn+1, which could also end up doing n multiplies, but doesn't require a divide.
Although this is actually valid C, think of it as pseudocode. A real implementation would check for negative n rather than looping through half the int numberspace. If you needed to apply this to an integer x rather than a floating point x, this would definitely be the way to go.
double polysum(int n, double x) {
double a = 1;
while (n--) a = x * a + 1;
return a;
}
public class Test {
public static void main(String args[]) {
int x = 2, n = 10;
Double sum = new Double(0);
for (int i = 0 ; i <= n ; i++) {
sum = sum + Math.pow(x, i);
}
System.out.println(sum);
}
}

Given the exp() function, how to implement the ln() function?

I came cross this question when I was in a CS job interview. I have no idea about it, let alone implement the code……
Could I get some tips?
P.S. exp() is the function y = e^x and ln() is y = ln(x)
You can find the value in log time by binary searching the answer. This is possible because log X is a monotonically increasing function.
(courtesy of WolframAlpha).
For example, if the value whose logarithm we have to calculate (assume it to be X) is greater than 1, then start with an assumption of answer = X. Raise the power e^answer and check if the value is greater than or smaller than X. Now based on whether the value you get is greater than or lesser than X, you can refine your limits. The search stops when you have reached within suitable ranges of your answer.
double log(double X){
double lo = 1;
double hi = X;
while(true){
double mid = (lo+hi)/2;
double val = power(e, mid);
if(val > X){
hi = mid;
}
if(val < X){
lo = mid;
}
if(abs(val-X) < error){
return mid;
}
}
}
Similarly, if the value of X is smaller than 1, then you can reduce this case to the case we have already considered, ie. when X is greater than 1. For example if X = 0.04, then
log 0.04 = log (4/100)
= (log 4) - (log 100)
If X is positive, then the logarithm can be found using Newton's method.
X_{0} = 0
X_{n+1} = X_{n} - (exp(X_{n}) - X) / (exp(X_{n})
Very fast convergence.
Adapting this answer to get X scaled in the range [0,e]. A few things we know about ln(x), ln(x) is only defined for 0 < x, ln(1)=0, the results can be any number from -infinity to +infinity. ln(x^a) = a * ln(x) in particular ln(x^(-1)) = - ln(x), ln(X/e) = ln(X)-ln(e) so ln(X) = ln(X/e) + 1.
double E = exp(1);
double ln(double X) {
if(X<0) return NaN;
// use recursion to get approx range
if(X<1) {
return - ln( 1 / X );
}
if(X>E) {
return ln(X/E) + 1;
}
// X is now between 1 and e
// Y is between 0 and 1
double lo = 0;
double hi = 1;
while(true){
double mid = (lo+hi)/2;
double val = exp(mid);
if(val > X){
hi = mid;
}
if(val < X){
lo = mid;
}
if(abs(val-X) < error){
return mid;
}
}
}
If you look at the actual implementations of mathematical functions in the libraries. They do quite a lot of prescaling work to narrow the ranges of input, probably more aggressive than is done here.

How to fix my numberOfDigits function

Came across some code where the number of digits was being determined by casting the number to a string then using a len().
Function numOfDigits_len(n As Long) As Long
numOfDigits_len = Len(Str(n)) - 1
End Function
Now although this works I knew it would be slow compared to any method that didn't use strings, so I wrote one that uses log().
Function numOfDigits_log(n As Long) As Long
numOfDigits_log = Int(Log(n) / Log(10)) + 1
End Function
Cut run time by 1/2 which was great but there was something weird happening in a specific case.
n numOfDigits_log(n)
===== ====================
999 3
1000 3
1001 4
It would not handle 1000 properly. I figured it is because of floating point and rounding issues.
Function numOfDigits_loop(ByVal n As Long) As Long
Do Until n = 0
n = n \ 10
numOfDigits_loop = numOfDigits_loop + 1
Loop
End Function
Wrote this which turned out to be ~10% slower as numbers got larger than 10^6 and seems to become slowly larger as n gets bigger. Which is fine if I was being pragmatic but I would like to find something more ideal.
Now my question is, is there a way to use the log() method accurately. I could do something like
Function numOfDigits_log(n As Long) As Long
numOfDigits_log = Int(Log(n) / Log(10) + 0.000000001) + 1
End Function
But it seems very "hacky". Is there a nicer way that's faster or as fast as the log() method?
Note: I realize this kind of optimization is pointless in a lot of cases but now that I've come across this I would like to "fix" it
I've answered this before, but I couldn't find it, so here's the basics:
int i = ... some number >= 0 ...
int n = 1;
if (i >= 100000000){i /= 100000000; n += 8;}
if (i >= 10000){i /= 10000; n += 4;}
if (i >= 100){i /= 100; n += 2;}
if (i >= 10){i /= 10; n += 1;}
That's in C, but you get the idea.
A while loop guarantees correctness, i.e. it doesn't use any floating point calculations
int numDigits = 0;
while(num != 0) {
num /= 10;
numDigits++;
}
You can also speed this up by using a larger divisor
int numDigits = 0;
if(num >= 100000 || num <= -100000) {
int prevNum;
while(num != 0) {
prevNum = num;
num /= 100000;
numDigits += 5;
}
num = prevNum;
numDigits -= 5;
}
while(num != 0) {
num /= 10;
numDigits++;
}
You'll love this.
We live in a base 10 number system! That means all you have to do is ROUND UP.
the length of some number ALWAYS = ceiling (log n). So for instance: 7456412 (a 7-digit number). Log (7456412) = 6.8...round up and you have 7. log (9999) = 3.9999. Round up and it's 4.
The special case is when you DON'T have to round, or when you have some power of 10. For instance: log(1000) = 3. if you can detect when you have a power of 10, add one to the log result and you win!
the way you could do this detection is something like
double log10;
int clog10;
int length;
log10 = (Log(n) / Log(10)); // can also use a private static final long hardcoded for Log(10)
clog10 = ceiling(log10);
if (Int(log10) == clog10)
length = clog10 + 1;
else
length = clog10;

Write a function to divide a number by 3 without using /, % and * operators. itoa() available?

I tried to solve it myself but I could not get any clue.
Please help me to solve this.
Are you supposed to use itoa() for this assignment? Because then you could use that to convert to a base 3 string, drop the last character, and then restore back to base 10.
Using the mathematical relation:
1/3 == Sum[1/2^(2n), {n, 1, Infinity}]
We have
int div3 (int x) {
int64_t blown_up_x = x;
for (int power = 1; power < 32; power += 2)
blown_up_x += ((int64_t)x) << power;
return (int)(blown_up_x >> 33);
}
If you can only use 32-bit integers,
int div3 (int x) {
int two_third = 0, four_third = 0;
for (int power = 0; power < 31; power += 2) {
four_third += x >> power;
two_third += x >> (power + 1);
}
return (four_third - two_third) >> 2;
}
The 4/3 - 2/3 treatment is used because x >> 1 is floor(x/2) instead of round(x/2).
EDIT: Oops, I misread the title's question. Multiply operator is forbidden as well.
Anyway, I believe it's good not to delete this answer for those who didn't know about dividing by non power of two constants.
The solution is to multiply by a magic number and then to extract the 32 leftmost bits:
divide by 3 is equivalent to multiply by 1431655766 and then to shift by 32, in C:
int divideBy3(int n)
{
return (n * 1431655766) >> 32;
}
See Hacker's Delight Magic number calculator.
x/3 = e^(ln(x) - ln(3))
Here's a solution implemented in C++:
#include <iostream>
int letUserEnterANumber()
{
int numberEnteredByUser;
std::cin >> numberEnteredByUser;
return numberEnteredByUser;
}
int divideByThree(int x)
{
std::cout << "What is " << x << " divided by 3?" << std::endl;
int answer = 0;
while ( answer + answer + answer != x )
{
answer = letUserEnterANumber();
}
}
;-)
if(number<0){ // Edited after comments
number = -(number);
}
quotient = 0;
while (number-3 >= 0){ //Edited after comments..
number = number-3;
quotient++;
}//after loop exits value in number will give you reminder
EDIT: Tested and working perfectly fine :(
Hope this helped. :-)
long divByThree(int x)
{
char buf[100];
itoa(x, buf, 3);
buf[ strlen(buf) - 1] = 0;
char* tmp;
long res = strtol(buf, &tmp, 3);
return res;
}
Sounds like homework :)
I image you can write a function which iteratively divides a number. E.g. you can model what you do with a pen and a piece of paper to divide numbers. Or you can use shift operators and + to figure out if your intermediate results is too small/big and iteratively apply corrections. I'm not going to write down the code though ...
unsigned int div3(unsigned int m) {
unsigned long long n = m;
n += n << 2;
n += n << 4;
n += n << 8;
n += n << 16;
return (n+m) >> 32;
}
int divideby3(int n)
{
int x=0;
if(n<3) { return 0; }
while(n>=3)
{
n=n-3;
x++;
}
return x;
}
you can use a property from the numbers: A number is divisible by 3 if its sum is divisible by3.
Take the individual digits from itoa() and then use switch function for them recursively with additions and itoa()
Hope this helps
This is very easy, so easy I'm only going to hint at the answer --
Basic boolean logic gates (and,or,not,xor,...) don't do division. Despite this handicap CPUs can do division. Your solution is obvious: find a reference which tells you how to build a divisor with boolean logic and write some code to implement that.
How about this, in some kind of Python like pseudo-code. It divides the answer into an integer part and a fraction part. If you want to convert it to a floating point representation then I am not sure of the best way to do that.
x = <a number>
total = x
intpart = 0
fracpart = 0
% Find the integer part
while total >= 3
total = total - 3
intpart = intpart + 1
% Fraction is what remains
fracpart = total
print "%d / 3 = %d + %d/3" % (x, intpart, fracpart)
Note that this will not work for negative numbers. To fix that you need to modify the algorithm:
total = abs(x)
is_neg = abs(x) != x
....
if is_neg
print "%d / 3 = -(%d + %d/3)" % (x, intpart, fracpart)
for positive integer division
result = 0
while (result + result + result < input)
result +=1
return result
Convert 1/3 into binary
so 1/3=0.01010101010101010101010101
and then just "multiply" whit this number using shifts and sum
There is a solution posted on http://bbs.chinaunix.net/forum.php?mod=viewthread&tid=3776384&page=1&extra=#pid22323016
int DividedBy3(int A) {
int p = 0;
for (int i = 2; i <= 32; i += 2)
p += A << i;
return (-p);
}
Please say something about that, thanks:)
Here's a O(log(n)) way to do it with no bit shifting, so it can handle numbers up-to and including your biggest register size.
(c-style code)
long long unsigned Div3 (long long unsigned n)
{
// base case:
if (n < 6)
return (n >= 3);
long long unsigned division = 0;
long long unsigned remainder = 0;
// Used for results for only a single power of 2
// Initialise for 2^0
long long unsigned tmp_div = 0;
long long unsigned tmp_rem = 1;
for (long long unsigned pow_2 = 1; pow_2 && (pow_2 <= n); pow_2 += pow_2)
{
if (n & pow_2)
{
division += tmp_div;
remainder += tmp_rem;
}
if (tmp_rem == 1)
{
tmp_div += tmp_div;
tmp_rem = 2;
}
else
{
tmp_div += tmp_div + 1;
tmp_rem = 1;
}
}
return division + Div3(remainder);
}
It uses recursion, but note that the number drops exponentially in size at each iteration, so the time complexity (TC) is really:
O(TC) = O(log(n) + log(log(n)) + log(log(log(n))) + ... + z)
where z < 6.
Proof that it's O(log(n)):
We note that the number at each recursion strictly decreases (by at least 1):
So series = [log(log(n))] + [log(log(log(n)))] + [...] + [z]) has at most log(log(n)) sums.
implies:
series <= log(log(n))*log(log(n))
implies:
O(TC) = O(log(n) + log(log(n))*log(log(n)))
Now we note for n sufficiently large:
sqrt(x) > log(x)
iff:
x/sqrt(x) > log(x)
implies:
x/log(x) > log(x)
iff:
x > log(x)*log(x)
So O(x) > O(log(x)*log(x))
Now let x = log(n)
implies:
O(log(n)) > O(log(log(n))*log(log(n)))
and given:
O(TC) = O(log(n) + log(log(n))*log(log(n)))
implies:
O(TC) = O(log(n))
Slow and naive, but it should work, if an exact divisor exists. Addition is allowed, right?
for number from 1 to input
if number == input+input+input
return number
Extending it for fractional divisors is left as an exercise to the reader.
Basically test for +1 and +2 I think...

Resources