I tried this:
static int myPow(int x)
{
int power = x + 1;
int num = 0;
for (int i = 0; i < power; i++)
{
num = x * i;
x = x + num;
}
return num;
}
how can I factorize the int x by x+1 without using Math.Pow?
The idea is to multiply X by X in a loop by X+1 times.
Follow the steps:
find the power (x + 1)
start the variable result with the x value (result = x)
loop i from 1 to power and for each loop multiply result by x, witch means x * x * x * x power times.
static int myPow(int x) {
int power = x + 1;
int result = x;
for (int i = 1; i < power; i++)
{
result *= x;
}
return result;
}
Take a look on the implementation it did on rextester
FYI factorization in math is this. Just for fun, the result can be calculated with Exponentiation by squaring:
static int myPow(int x, int y)
{
if (y < 0) { throw new ArgumentException("y has to be nonnegative"); }
int result = 1;
while (y > 0)
{
if ((y & 1) == 1)
{
result *= x;
}
x = x * x;
y >>= 1;
}
return result;
}
You can use a technique called exponentiation by squaring, which is quite beautiful and is also faster, it takes O(lg k) time, where k is exponent:
static int square(int n){
return n * n;
}
static int pow(int n, int k){
if(k == 1) return n;
if(k % 2 == 1) return n * pow(n, k-1);
return square(pow(n, k/2));
}
then, if you want to get x^(x+1), you just need yo call pow(x, x+1).
small, fast and simple as that :)
Related
Find x in 2^x = n.
This is what I am trying to do.(It is not for any specific purpose. It just looks good.)
This is what I wrote but it doesn't work.
public double f(double x)
{
double result = 0;
double increaser = 1;
double subtract = result - increaser;
double add = result + increaser;
while(true)
{
if((Math.Pow(2,result) == x) || increaser == 0.0001)
{
break;
}
double sP = Math.Abs(Math.Pow(2,subtract) - x);
double aP = Math.Abs(Math.Pow(2,add) - x);
double nP = Math.Abs(Math.Pow(2,result) - x);
if((sP < nP) && (sP < aP))
{
result -= increaser;
}
else if((aP < nP) && (aP < sP))
{
result += increaser;
}
else if((nP < sP) && (nP < aP))
{
increaser = increaser / 10;
}
}
return result;
}
This function is called the logarithm:
return Math.Log2(n);
For the general case, you can use two formulae for this:
if bx = n, then x = logbn; and
logba = logxa/logxb.
Since what you're looking for is x in 2x = n, that is x = log2n = logen/loge2, something that can be done with:
public double f(double x) {
return Math.Log(x) / Math.Log(2);
}
Of course, that's for the case where you have a limited set of logarithm bases (such as 10 or e). Since C# provides a call that will handle any base, you can bypass the division operation:
public double f(double x) {
return Math.Log(x, 2);
}
or even use the base-2 one:
public double f(double x) {
return Math.Log2(x);
}
So I currently have 2 values x and y and I want x to be decremented/incremented by y until it gets to 0 without going over.
float x = 9;
float y = 4;
if (x != 0) {
if (x > 0) {
x -= y;
}
else if (x < 0) {
x += y;
}
}
If this was to run x would be subtracted by y 3 times leaving the value of x at -2 in which the next frame it will run again and add y which will again go over.
You could change the implementation as follows by introducing clipping at 0 after the subtraction or addition.
if (x != 0) {
if (x > 0) {
x -= y;
x = Math.Max(x, 0.0f);
}
else if (x < 0) {
x += y;
x = Math.Min(x, 0.0f);
}
}
Not sure if I understand correctly, but if you want x to be decremented/incremented by y until it gets to 0 without going over, this should do it:
for( ; x>=0; x = x - y);
x = x + y;
This function will give you this results in comments, for wrong parameters it will avoid going to infinity and return X:
//[9, 4] = 1
//[-9, -4] = -1
private static float Unnamed(float x, float y)
{
float tmp = x;
float result = x;
while (true)
{
tmp -= y;
if (y > 0)
{
if (tmp > 0 && tmp < x)
result = tmp;
else
break;
}
else
{
if (tmp < 0 && tmp > x)
result = tmp;
else
break;
}
}
return result;
}
Okay so based on #Codor's answer I got this
private float Approach(float value, float targetValue, float step) {
float result;
if (value < targetValue) {
result = Mathf.Min (value + step, targetValue);
} else {
result = Mathf.Max (value - step, targetValue);
}
return result;
}
which worked fine and does exactly what I wanted and will never go past the target value. And then I came across an already built in function that does exactly what I wanted as well Mathf.MoveTowards(value, targetValue, step).
You can do this using something like this :
if ( x != 0 )
{
x = x < 0 ? Math.Min(x + y, 0) : Math.Max(x - y, 0);
}
how to find the min and max for quadratic equation using c# ??
f(x,y) = x^2 + y^2 + 25 * (sin(x)^2 + sin(y)^2) ,where (x,y) from (-2Pi, 2Pi) ??
in the manual solving I got min is = 0 , max = 8Pi^2 = 78.957 .
I tried to write the code based on liner quadratic code but something goes totally wrong
this code give the min = -4.?? and the max = 96 could you help to know where is my mistake please ??
I uploaded the code to dropbox if anyone can have look : https://www.dropbox.com/s/p7y6krk2gk29i9e/Program.cs
double[] X, Y, Result; // Range array and result array.
private void BtnRun_Click(object sender, EventArgs e)
{
//Set any Range for the function
X = setRange(-2 * Math.PI, 2 * Math.PI, 10000);
Y = setRange(-2 * Math.PI, 2 * Math.PI, 10000);
Result = getOutput_twoVariablesFunction(X, Y);
int MaxIndex = getMaxIndex(Result);
int MinIndex = getMinIndex(Result);
TxtMin.Text = Result[MinIndex].ToString();
TxtMax.Text = Result[MaxIndex].ToString();
}
private double twoVariablesFunction(double x,double y)
{
double f;
//Set any two variables function
f = Math.Pow(x, 2) + Math.Pow(y, 2) + 25 * (Math.Pow(Math.Sin(x), 2) + Math.Pow(Math.Sin(y), 2));
return f;
}
private double[] setRange(double Start, double End, int Sample)
{
double Step = (End - Start) / Sample;
double CurrentVaue = Start;
double[] Array = new double[Sample];
for (int Index = 0; Index < Sample; Index++)
{
Array[Index] = CurrentVaue;
CurrentVaue += Step;
}
return Array;
}
private double[] getOutput_twoVariablesFunction(double[] X, double[] Y)
{
int Step = X.Length;
double[] Array = new double[Step];
for (int Index = 0; Index < X.Length ; Index++)
{
Array[Index] = twoVariablesFunction(X[Index], Y[Index]);
}
return Array;
}
private int getMaxIndex(double[] ValuesArray)
{
double M = ValuesArray.Max();
int Index = ValuesArray.ToList().IndexOf(M);
return Index;
}
private int getMinIndex(double[] ValuesArray)
{
double M = ValuesArray.Min();
int Index = ValuesArray.ToList().IndexOf(M);
return Index;
}
Do you want to compute (sin(x))^2 or sin(x^2)? In your f(x,y) formula it looks like (sin(x))^2, but in your method twoVariablesFunction like sin(x^2).
Is there a built in function that would allow me to calculate the modular inverse of a(mod n)?
e.g. 19^-1 = 11 (mod 30), in this case the 19^-1 == -11==19;
Since .Net 4.0+ implements BigInteger with a special modular arithmetics function ModPow (which produces “X power Y modulo Z”), you don't need a third-party library to emulate ModInverse. If n is a prime, all you need to do is to compute:
a_inverse = BigInteger.ModPow(a, n - 2, n)
For more details, look in Wikipedia: Modular multiplicative inverse, section Using Euler's theorem, the special case “when m is a prime”. By the way, there is a more recent SO topic on this: 1/BigInteger in c#, with the same approach suggested by CodesInChaos.
int modInverse(int a, int n)
{
int i = n, v = 0, d = 1;
while (a>0) {
int t = i/a, x = a;
a = i % x;
i = x;
x = d;
d = v - t*x;
v = x;
}
v %= n;
if (v<0) v = (v+n)%n;
return v;
}
The BouncyCastle Crypto library has a BigInteger implementation that has most of the modular arithmetic functions. It's in the Org.BouncyCastle.Math namespace.
Here is a slightly more polished version of Samuel Allan's algorithm. The TryModInverse method returns a bool value, that indicates whether a modular multiplicative inverse exists for this number and modulo.
public static bool TryModInverse(int number, int modulo, out int result)
{
if (number < 1) throw new ArgumentOutOfRangeException(nameof(number));
if (modulo < 2) throw new ArgumentOutOfRangeException(nameof(modulo));
int n = number;
int m = modulo, v = 0, d = 1;
while (n > 0)
{
int t = m / n, x = n;
n = m % x;
m = x;
x = d;
d = checked(v - t * x); // Just in case
v = x;
}
result = v % modulo;
if (result < 0) result += modulo;
if ((long)number * result % modulo == 1L) return true;
result = default;
return false;
}
There is no library for getting inverse mod, but the following code can be used to get it.
// Given a and b->ax+by=d
long[] u = { a, 1, 0 };
long[] v = { b, 0, 1 };
long[] w = { 0, 0, 0 };
long temp = 0;
while (v[0] > 0)
{
double t = (u[0] / v[0]);
for (int i = 0; i < 3; i++)
{
w[i] = u[i] - ((int)(Math.Floor(t)) * v[i]);
u[i] = v[i];
v[i] = w[i];
}
}
// u[0] is gcd while u[1] gives x and u[2] gives y.
// if u[1] gives the inverse mod value and if it is negative then the following gives the first positive value
if (u[1] < 0)
{
while (u[1] < 0)
{
temp = u[1] + b;
u[1] = temp;
}
}
Because of asking my last question, I've changed my code to use return. I always have this problem with return: I know I should use return (where I comment in code below) but I dont know how should I define it to work? Thanks for your help.
public double bigzarb(int u, int v)
{
double n;
int x=0;
int y;
int w=0;
int z;
string[] i = textBox7.Text.Split(',');
int[] nums = new int[i.Length];
for (int counter = 0; counter < i.Length; counter++)
{
nums[counter] = Convert.ToInt32(i[counter]);
}
u = nums[0];
double firstdigits =Math.Floor(Math.Log10(u) + 1);
v = nums[1];
double seconddigits = Math.Floor(Math.Log10(v) + 1);
if (firstdigits >= seconddigits)
{
n = firstdigits;
}
else
{
n = seconddigits;
}
if (u == 0 || v == 0)
{
MessageBox.Show("the Multiply is 0");
}
string threshold = textBox9.Text;
int intthreshold = Convert.ToInt32(threshold);
int intn = Convert.ToInt32(n);
if (intn <= intthreshold)
{
double uv = u * v;
string struv = uv.ToString();
MessageBox.Show(struv);
///i know here should be a return but i dont know how to define it to work
}
else
{
int m = Convert.ToInt32(Math.Floor(n / 2));
x = u % 10 ^ m;
y = u / 10 ^ m;
w = v % 10 ^ m;
z = v / 10 ^ m;
return bigzarb(x, w) *Math.Pow(10,m) +(bigzarb(x,w)+bigzarb(w,y))*Math.Pow(10,m) +bigzarb(y,z);
}
}
arash, your problem isn't with that return, your problem is bigzarb() is declared as void which means it has no returning value yet you use it in your last line as bigzarb(x,w) * .... which will give you an error. Also, since you declared your bigzarb() as void, you cant return a value in it. Also ^ doesn't mean power of in .net, you should use Math.Power instead.
Edit: You should change your method from void bigzarb() to double bigzarb() and replace ^ with Math.Power and retry to see if yit works.
Last edit: Change your method return type to double from int and change the last line to:
return bigzarb(x, w) * Math.Pow(Convert.ToDouble(10), Convert.ToDouble(m)) + (bigzarb(x, w) + bigzarb(w, y)) * Math.Pow(Convert.ToDouble(10), Convert.ToDouble(m)) + bigzarb(y, z);
If your method is defined to "return void", you can't return some value.
So change that "void" into "int" or "double", whatever type of value you want to return.
The next question is what value do you want to return in that spot? Return that.
By the way: if you really don't want to return a value (ever!) then that "void" is correct and you should only use "return" without value (or let the method run until the last line of the method).
my tip to you is to structure your code, extract some of the code to separate functions with meaningful names and also rename your variables to sometging meaningful. That would make it easier to read, understand and you get a better "flow" in your code. Also, you should complement your text with an actual question. Try to insert an extra return statement in the if code block, it is perfectly fine to have multiple return statements.
if(logic check)
{
return something;
}
else
{
return something else;
}
You need to have return either in both statements or one return after the if-else block, otherwise you'll get somekind of compiler error saying that not all code paths returns a result or something similar.
You have only one return and it's a recursive call (calling itself) --> stack overflow! You need to have another return somewhere without a recursive call
public int bigzarb(int u, int v)
{
double n;
int x = 0;
int y;
int w = 0;
int z;
string[] i = textBox1.Text.Split(',');
int[] nums = new int[i.Length];
for (int counter = 0; counter < i.Length; counter++)
{
nums[counter] = Convert.ToInt32(i[counter]);
}
u = nums[0];
double firstdigits = Math.Floor(Math.Log10(u) + 1);
v = nums[1];
double seconddigits = Math.Floor(Math.Log10(v) + 1);
if (firstdigits >= seconddigits)
{
n = firstdigits;
}
else
{
n = seconddigits;
}
if (u == 0 || v == 0)
{
MessageBox.Show("the Multiply is 0");
}
//string threshold = textBox9.Text;
int intthreshold = Convert.ToInt32(textBox9.Text);//Edited by me
int intn = Convert.ToInt32(n);
if (intn <= intthreshold)
{
double uv = u * v;
string struv = uv.ToString();
MessageBox.Show(struv);
///i know i should use return here but how can i implement that to work?
}
else
{
int m = Convert.ToInt32(Math.Floor(n / 2));
x = u % 10 ^ m;
y = u / 10 ^ m;
w = v % 10 ^ m;
z = v / 10 ^ m;
return bigzarb(x, w) * (10 ^ m) + (bigzarb(x, w) + bigzarb(w, y)) * 10 ^ m + bigzarb(y, z);
}
return 0;
}
Its a confusing one.since your function contains Void as return type
Declare the integer variable for returning the values
Ex:
public int func()
{
int l_nData = 0;
if(condition)
{
l_nData = 1;
return l_nData;
}
else
{
l_nData = 2;
return l_nData;
}
return l_nData;
}