Say we have two values,
int a = 2489;
int b = 3019201;
From these two values i want to create an if statement to check if the two values have the same ones digit. i.e. 248(9) and 301920(1). In this case they dont obviously.
But i want to make an if to check this, how would i go ahead and do this?
Check if the difference of a and b is divisible by 10 without remainder (modulo):
bool hasSameOnes = (a - b) % 10 == 0
Use the modulo operator:
if ( (a%10) == (b%10) )
{
}
Related
I have number list like below and I should check a condition to get most suitable match.
List<int> numbers= new List<int>();
numbers.Add(1000);
numbers.Add(3000);
numbers.Add(5500);
numbers.Add(7000);
If I send a value to check it should check like below examples
Scenario 1:
If I send a value less than or equal 1000 to check, it should return 1000
Scenario 2:
If I send a value between 1001 - 3000 to check, it should return 3000
Scenario 3:
If I send a value between 3001 - 5500 to check, it should return 5500
Scenario 4:
If I send a value between 5501 - 7000 to check, it should return 7000
Scenario 5:
If I send a value above 7000 to check, it should return nothing.
Can I do this with Linq? or what is the most efficient way to do this?
Update: the numbers in maxCheckPoint is dynamic and it can be any values. So we cannot hard coded and check
You can do this with LINQ:
int input = 1000;
int? result = numbers
.OrderBy(n => n) // get the numbers in ascending order
.SkipWhile(n => n < input) // skip until the remaining set >= input
.Cast<int?>() // cast to nullable int
.FirstOrDefault(); // take the first or default entry (if no items remain, it will be null)
Well, it's too late and my solution is far away from perfect, but:
int number = 400; //imput number
int closest = numbers.Aggregate((x, y) => Math.Abs(x - number) < Math.Abs(y - number) ? x : y); // searching the closer one
int compare;
try{
if (numbers.IndexOf(closest) != 0)
{
compare = Math.Max(closest, numbers[numbers.IndexOf(closest) + 1]); // if it's not 0th and last
}
else
{ compare = closest; // if closest with index 0}
}// check which closest number is bigger
catch{
compare = closest; // if closest is last
}
Console.WriteLine(compare);
I am very new to C# and have been set a task to make a program that asks for a user input of a number and then says if that number is odd or even. How can I do that?
You need to figure how to check if a number is odd or even. How can do, you ask?
You may not have learned this yet, but modulus is the simplest way to do it. It uses the character % and it basically acts as a division, but instead of telling what value each parts of the division equals, it tells you what is left from the division. Coming from that, you know that if the number divided by % 2 is 0, your number is even because there is nothing left. 4 / 2 = 2 vs 4 % 2 = 0
My example here is not the shortest or fastest, but is easier to understand for a beginner
Console.WriteLine("Enter your number : ");
string number = Console.ReadLine();
Int32.Parse(number);
if(number % 2 == 0)
{
Console.WriteLine("Your number is even.");
}
else
{
Console.WriteLine("Your number is odd.");
}
Have a look at the remainder (modulus) operator.
An example:
int userInput = // get your input
bool isEven = userInput % 2 == 0;
An even number will have a remainder of 0 when divided by 2.
In one line
Console.WriteLine(int.Parse(Console.ReadLine()) % 2 == 0 ? "even":"odd");
Is it possible to re-write the following so that it doesn't contain any conditional statements? I'm thinking there might be some clever trick using something like bitwise operations?
int a = // some value
int b = // some other value between 0 and max int
if(b >= 3)
{
return a + 1;
}
else
{
return a;
}
EDIT: to be clear, I'm not looking for a generic way of removing conditionals. I'm looking for a trick to remove the conditionals from this very specific code. Think of it as an academic puzzle.
To give an example, one way to remove conditionals (which happens to yield perf gains in some situations) is to precompute a lookup table and index into that with b instead. In this particular case this is tricky because b could be a very large number. Is there another way?
Here you go
return a - ((2 - b) >> 31);
Explanation:
r = 2 - b, < 0 (i.e. high bit set) for b >= 3
r >> 31, = -1 for b >= 3, 0 otherwise
uint a = // some value
uint b = // some other value between 0 and max int
bool c = b & 0xFFFC
return a + Convert.ToInt32(c);
The fastest will probably be as bitwise operations tend to be very fast
uint a = // some value
uint b = // some other value between 0 and max int
return (b & 0xFFFC) ? a+1 : a;
You could make it better by doing this:
int a = // some value
int b = // some other value between 0 and max int
return (b >= 3) ? (a+1) : a;
?: operator. (but yet it contains conditional statement.)
return b >= 3 ? a + 1 : a;
or
return a + (b >= 3 ? 1 : 0);
Is it possible to re-write the following so that it doesn't contain any conditional statements?
It is not possible to make it work out of no where. you must check this condition any way. There is no magic.
If you want to make your program faster by removing this condition then you picked wrong way. this is micro optimization.
I have a function called Slice. It consumes 2 values. First Node value and a second node value. I'm trying to find the value between [First,Second] inclusively that makes function G(x) go to zero or very near, closest by 2 decimal places. I can solve this problem using an iterative function starting at first number and incrementing by .01 but this could take a very long time.
I'm trying to have it with a binary run time. The tricky part is that I don't know which slice to take after I find the mid point. If I can get some tips or suggestions to continue please.
public double Slice(decimal first, decimal last)
{
double firstNodeValue = FinalOptionDecider(first);
double midNodeValue = FinalOptionDecider((last + first) / 2);
double lastNodeValue = FinalOptionDecider(last);
}
Binary search relies on sorted data to make the decision on which half to search next. So unless the function you want to pass your data through also retains your data in a sorted order, you cannot use binary search.
You have two options:
Give up on binary search and just do a linear search
Process all the inputs, sort and binary search the outputs (you can pair the input and output together in dictionary to retrieve the input).
As a general problem for an arbitrary function, this can be very difficult to solve. It becomes a lot easier if you can make certain assumptions. The algorithm you've sort of started to stub out is called a bisection algorithm.
First you need to bracket the value that you're looking for. So if you want FinalOptionDecider(x) to return zero, your firstNodeValue and lastNodeValue must be positive and negative. If they're both positive or both negative, you've failed to bracket the value that you want and you can't make any guarantee that searching between first and last will find an answer. And you also won't be able to guarantee that you can make the decision described in the next paragraph. So check for that first.
That condition is basically your answer... when you get the midNodeValue you need to check and see if your desired value is between firstNodeValue and midNodeValue or if it's between midNodeValue and lastNodeValue. Depending on which it is, you need to do a slice on that interval again. Repeat until you reach the desired precision.
If your function has multiple zeroes (like g(x) = x^2 - 1 does) then you will only find one of the zeroes.
You're just looking for a root-finding algorithm. The one you've started implementing here is just the Bisection method. Bisection isn't the fastest, but it has the major advantage that it's simple and guaranteed to converge to a root in the specified interval provided the function changes sign over the interval and the function is continuous (thus, by the intermediate value theorem, a root is guaranteed to exist in the interval. Here's a simple, somewhat generic implementation of the bisection method:
public static decimal FindRoot( decimal first, decimal last, Func<decimal, double> f, double value, decimal tolerance = 0.01m )
{
double fa = f( first );
double fb = f( last );
if( fa * fb > 0 )
{
throw new ArgumentException( "Interval not guaranteed to contain root." );
}
else if( fa == 0 )
{
return first;
}
else if( fb == 0 )
{
return last;
}
while( Math.Abs( first - last ) > tolerance )
{
decimal mid = ( first + last ) / 2;
double fc = f( mid );
if( fc * fb < 0 )
{
first = mid;
fa = fc;
}
else if( fc * fa < 0 )
{
last = mid;
fb = fc;
}
else
{
return mid;
}
}
return ( first - last ) * (decimal) ( fa / ( fb - fa ) ) + first;
}
The binary search is all about narrowing down an interval until the interval only consists of one value. I don't know what you mean by random but a binary sort can only be performed on a sorted dataset. Remember that it is almost always faster to search randomly than to sort and then search!
I have tried to write a code for Fermat primality test, but apparently failed.
So if I understood well: if p is prime then ((a^p)-a)%p=0 where p%a!=0.
My code seems to be OK, therefore most likely I misunderstood the basics. What am I missing here?
private bool IsPrime(int candidate)
{
//checking if candidate = 0 || 1 || 2
int a = candidate + 1; //candidate can't be divisor of candidate+1
if ((Math.Pow(a, candidate) - a) % candidate == 0) return true;
return false;
}
Reading the wikipedia article on the Fermat primality test, You must choose an a that is less than the candidate you are testing, not more.
Furthermore, as MattW commented, testing only a single a won't give you a conclusive answer as to whether the candidate is prime. You must test many possible as before you can decide that a number is probably prime. And even then, some numbers may appear to be prime but actually be composite.
Your basic algorithm is correct, though you will have to use a larger data type than int if you want to do this for non-trivial numbers.
You should not implement the modular exponentiation in the way that you did, because the intermediate result is huge. Here is the square-and-multiply algorithm for modular exponentiation:
function powerMod(b, e, m)
x := 1
while e > 0
if e%2 == 1
x, e := (x*b)%m, e-1
else b, e := (b*b)%m, e//2
return x
As an example, 437^13 (mod 1741) = 819. If you use the algorithm shown above, no intermediate result will be greater than 1740 * 1740 = 3027600. But if you perform the exponentiation first, the intermediate result of 437^13 is 21196232792890476235164446315006597, which you probably want to avoid.
Even with all of that, the Fermat test is imperfect. There are some composite numbers, the Carmichael numbers, that will always report prime no matter what witness you choose. Look for the Miller-Rabin test if you want something that will work better. I modestly recommend this essay on Programming with Prime Numbers at my blog.
You are dealing with very large numbers, and trying to store them in doubles, which is only 64 bits.
The double will do the best it can to hold your number, but you are going to loose some accuracy.
An alternative approach:
Remember that the mod operator can be applied multiple times, and still give the same result.
So, to avoid getting massive numbers you could apply the mod operator during the calculation of your power.
Something like:
private bool IsPrime(int candidate)
{
//checking if candidate = 0 || 1 || 2
int a = candidate - 1; //candidate can't be divisor of candidate - 1
int result = 1;
for(int i = 0; i < candidate; i++)
{
result = result * a;
//Notice that without the following line,
//this method is essentially the same as your own.
//All this line does is keeps the numbers small and manageable.
result = result % candidate;
}
result -= a;
return result == 0;
}