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);
}
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 :)
How to shift all the whole numbers in a double to the right of the point ?
Example i have 5342, i want the function to return 0.5342. I do not know the number of digits in the double, it's randomly generated. Should be fairly easy but i can't find any answers.
private static void Main(string[] args)
{
Console.WriteLine(MyFunction(5127));
Console.WriteLine(MyFunction(1));
Console.WriteLine(MyFunction(51283271));
Console.WriteLine(MyFunction(-512));
Console.WriteLine(MyFunction(0));
}
public static double MyFunction(double myNumber)
{
return Math.Floor(myNumber) / Math.Pow(10, Math.Abs(myNumber).ToString().Length);
}
This sounds like a pretty bizarre task, to be honest, but you could use:
while (Math.Abs(value) >= 1)
{
value = value / 10;
}
That will go into an infinite loop if the input is infinity though - and you may well lose information as you keep dividing. The latter point is important - if what you're really interested in is the decimal representation, you should consider using decimal instead of double.
You could potentially use a mixture of Math.Log and Math.Pow to do it, but the above is probably what I'd start with.
This will get you most of the way there
public static string test()
{
double dub = 5432;
string dubTxt = dub.ToString();
string text = "0.";
string test = string.Concat(text + dubTxt);
if (1 == 1)
{
MessageBox.Show(test);
return test;
}
}
You will have to develop more if statements to handle the negative numbers.
public static string test()
{
double dub = 5432;
string dubTxt = dub.ToString();
string text = "0.";
string test = string.Concat(text + dubTxt);
if (dub < 0)
{
//Do this code instead
}
}
Good Luck. Please bump me if you choose it!! I need the cred so I can do other junk. :-D
Just divide by 10 until the number is less than 1.
public static double SomeMethod(double n)
{
double d = n;
bool isNegative = (d < 0);
if(isNegative)
d = d * -1;
while(d >= 1)
d = d/10;
if(isNegative)
d = d * -1;
return d;
}
Alternative (and more precise) option:
public static double SomeMethod2(double n)
{
double d = n;
bool isNegative = (d < 0);
if(isNegative)
d = d * -1;
int numberOfDigits = ((int)d).ToString().Length;
int divisor = 1;
for(int i = 0; i < numberOfDigits; i++)
divisor = divisor * 10;
d = d/divisor;
if(isNegative)
d = d * -1;
return d;
}
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;
}
}
The method should work like Math.Max(), but take 3 or more int parameters.
You could use Enumerable.Max:
new [] { 1, 2, 3 }.Max();
Well, you can just call it twice:
int max3 = Math.Max(x, Math.Max(y, z));
If you find yourself doing this a lot, you could always write your own helper method... I would be happy enough seeing this in my code base once, but not regularly.
(Note that this is likely to be more efficient than Andrew's LINQ-based answer - but obviously the more elements you have the more appealing the LINQ approach is.)
EDIT: A "best of both worlds" approach might be to have a custom set of methods either way:
public static class MoreMath
{
// This method only exists for consistency, so you can *always* call
// MoreMath.Max instead of alternating between MoreMath.Max and Math.Max
// depending on your argument count.
public static int Max(int x, int y)
{
return Math.Max(x, y);
}
public static int Max(int x, int y, int z)
{
// Or inline it as x < y ? (y < z ? z : y) : (x < z ? z : x);
// Time it before micro-optimizing though!
return Math.Max(x, Math.Max(y, z));
}
public static int Max(int w, int x, int y, int z)
{
return Math.Max(w, Math.Max(x, Math.Max(y, z)));
}
public static int Max(params int[] values)
{
return Enumerable.Max(values);
}
}
That way you can write MoreMath.Max(1, 2, 3) or MoreMath.Max(1, 2, 3, 4) without the overhead of array creation, but still write MoreMath.Max(1, 2, 3, 4, 5, 6) for nice readable and consistent code when you don't mind the overhead.
I personally find that more readable than the explicit array creation of the LINQ approach.
Linq has a Max function.
If you have an IEnumerable<int> you can call this directly, but if you require these in separate parameters you could create a function like this:
using System.Linq;
...
static int Max(params int[] numbers)
{
return numbers.Max();
}
Then you could call it like this: max(1, 6, 2), it allows for an arbitrary number of parameters.
As generic
public static T Min<T>(params T[] values) {
return values.Min();
}
public static T Max<T>(params T[] values) {
return values.Max();
}
off topic but here is the formula for middle value.. just in case someone is looking for it
Math.Min(Math.Min(Math.Max(x,y), Math.Max(y,z)), Math.Max(x,z));
Let's assume that You have a List<int> intList = new List<int>{1,2,3} if You want to get a max value You could do
int maxValue = intList.Max();
Maximum element value in priceValues[] is maxPriceValues :
double[] priceValues = new double[3];
priceValues [0] = 1;
priceValues [1] = 2;
priceValues [2] = 3;
double maxPriceValues = priceValues.Max();
If, for whatever reason (e.g. Space Engineers API), System.array has no definition for Max nor do you have access to Enumerable, a solution for Max of n values is:
public int Max(int[] values) {
if(values.Length < 1) {
return 0;
}
if(values.Length < 2) {
return values[0];
}
if(values.Length < 3) {
return Math.Max(values[0], values[1]);
}
int runningMax = values[0];
for(int i=1; i<values.Length - 1; i++) {
runningMax = Math.Max(runningMax, values[i]);
}
return runningMax;
}
You could try this code:
private float GetBrightestColor(float r, float g, float b) {
if (r > g && r > b) {
return r;
} else if (g > r && g > b) {
return g;
} else if (b > r && b > g) {
return b;
}
}
This function takes an array of integers. (I completely understand #Jon Skeet's complaint about sending arrays.)
It's probably a bit overkill.
public static int GetMax(int[] array) // must be a array of ints
{
int current_greatest_value = array[0]; // initializes it
for (int i = 1; i <= array.Length; i++)
{
// compare current number against next number
if (i+1 <= array.Length-1) // prevent "index outside bounds of array" error below with array[i+1]
{
// array[i+1] exists
if (array[i] < array[i+1] || array[i] <= current_greatest_value)
{
// current val is less than next, and less than the current greatest val, so go to next iteration
continue;
}
} else
{
// array[i+1] doesn't exist, we are at the last element
if (array[i] > current_greatest_value)
{
// current iteration val is greater than current_greatest_value
current_greatest_value = array[i];
}
break; // next for loop i index will be invalid
}
// if it gets here, current val is greater than next, so for now assign that value to greatest_value
current_greatest_value = array[i];
}
return current_greatest_value;
}
Then call the function :
int highest_val = GetMax (new[] { 1,6,2,72727275,2323});
// highest_val = 72727275
You can use if and else if method for three values but it would be much easier if you call call twice Math.Max method like this
Console.WriteLine("Largest of three: " + Math.Max(num1, Math.Max(num2, num3)));
Console.WriteLine("Lowest of three: " + Math.Min(num1, Math.Min(num2, num3)));
If you don't want to repeatedly calling the Max function, can do like this
new List<int>() { A, B, C, D, X, Y, Z }.Max()
in case you need sorting as well:
var side = new double[] {5,3,4}
Array.Sort(side);
//side[2] is a maximum
as an another variant:
T[] GetMax<T>(int number, List<T> source, T minVal)
{
T[] results = new T[number];
for (int i = 0; i < number; i++)
{
results[i] = minVal;
}
var curMin = minVal;
foreach (var e in source)
{
int resComp = Comparer.DefaultInvariant.Compare(curMin, e);
if (resComp < 0)
{
int minIndex = Array.IndexOf(results, curMin);
results[minIndex] = e;
curMin = results.Min();
}
}
return results;
}
var source = new int[] { 5, 5, 1, 2, 4, 3 }.ToList();
var result = GetMax(3, source, int.MinValue);