Value not getting right answer - c#

int c;
int f = 20;
c = 5 / 9 * (f - 32);
Console.WriteLine(c);
Console.ReadLine();
If I run this code c ends up being 0, which is wrong. Can anyone tell me why?

Because your calculation is being done in integer type. I believe c is double type variable.
c = 5d / 9 * (f - 32.0);
use 32.0 or 32d so that one of the operands is double, also do the same for 5/9.
Also you need to define c as double.

the problem is in the following line;
5 / 9
because c and f are integers.
For instance, if I asked you to divide 11 to 10; you will tell me the result is 1.1. Assume that you do not know about floating point arithmetic, then you will say either it is not possible to divide 11 to 10; or you will say it is 1. Runtime environment does the same, it says it is 0 since you are declaring an integer.

Habib already explained what is happening. Here is what you could do if you don't want to change c to a float or double:
c = (int)Math.Round(5.0 / 9.0 * (f - 32.0));

Related

Why print(70 * (50 / 100)) returns 0? [duplicate]

This question already has answers here:
1/252 = 0 in c#?
(3 answers)
Closed 5 years ago.
Why it returns 0?
print(70 * (50 / 100));
70 * 0,5 = 35
I don't know why this is happening. Or did I make some stupid mistake either ... I don't know
The 50/100 is a division between integers. Since 50<100, the result is 0 and consequently 70*(50/100) results in 0.
If you want to avoid this, you have to cast one of them as a double.
70 * (50 / (double)100)
or
70 * ((double) 50/ 100)
When you divide two integers, the result is always an integer. For example, the result of 7 / 3 is 2.
So on 50/100 is equal to 0.35 and because you are diving two Integers, it will ignore decimal places so it's gonna be a zero - 0, so computer see it as : (ignoring .35)
70 * 0 = 0
P.S
Maybe you could explore little bit about invoking Decimal.Divide, your int arguments get implicitly converted to Decimals so .35 won't be ignored.
You can also enforce non-integer division on int arguments by explicitly casting at least one of the arguments to a floating-point type, e.g.:
int a = 42;
int b = 23;
double result = (double)a / b;
That's how it comes.. :)
Because / will output int and not double value. The result should be 0.5 and 0 will be taken as int then it will be multiplied by 70 and the result will be 0.
You need to make a cast as follows :
double x = 50/(double)100 ;
Then:
print(70 * x);
50 / 100 is 0 and 70 * 0 is 0.

1/BigInteger in c#

I want to make
BigInteger.ModPow(1/BigInteger, 2,5);
but 1/BigInteger always return 0, which causes, that the result is 0 too. I tried to look for some BigDecimal class for c# but I have found nothing. Is there any way how to count this even if there is no BigDecimal?
1/a is 0 for |a|>1, since BigIntegers use integer division where the fractional part of a division is ignored. I'm not sure what result you're expecting for this.
I assume you want to modular multiplicative inverse of a modulo m, and not a fractional number. This inverse exists iff a and m are co-prime, i.e. gcd(a, m) = 1.
The linked wikipedia page lists the two standard algorithms for calculating the modular multiplicative inverse:
Extended Euclidean algorithm, which works for arbitrary moduli
It's fast, but has input dependent runtime.
I don't have C# code at hand, but porting the pseudo code from wikipedia should be straight forward.
Using Euler's theorem:
This requires knowledge of φ(m) i.e. you need to know the prime factors of m. It's a popular choice when m is a prime and thus φ(m) = m-1 when it simply becomes . If you need constant runtime and you know φ(m), this is the way to go.
In C# this becomes BigInteger.ModPow(a, phiOfM-1, m)
The overload of the / operator chosen, is the following:
public static BigInteger operator /(
BigInteger dividend,
BigInteger divisor
)
See BigInteger.Division Operator. If the result is between 0 and 1 (which is likely when dividend is 1 as in your case), because the return value is an integer, 0 is returned, as you see.
What are you trying to do with the ModPow method? Do you realize that 2,5 are two arguments, two and five, not "two-point-five"? Is your intention "take square modulo 5"?
If you want floating-point division, you can use:
1.0 / (double)yourBigInt
Note the cast to double. This may lose precision and even "underflow" to zero if yourBigInt is too huge.
For example you need to get d in the next:
3*d = 1 (mod 9167368)
this is equally:
3*d = 1 + k * 9167368, where k = 1, 2, 3, ...
rewrite it:
d = (1 + k * 9167368)/3
Your d must be the integer with the lowest k.
Let's write the formula:
d = (1 + k * fi)/e
public static int MultiplicativeInverse(int e, int fi)
{
double result;
int k = 1;
while (true)
{
result = (1 + (k * fi)) / (double) e;
if ((Math.Round(result, 5) % 1) == 0) //integer
{
return (int)result;
}
else
{
k++;
}
}
}
let's test this code:
Assert.AreEqual(Helper.MultiplicativeInverse(3, 9167368), 6111579); // passed

How to get integer quotient when divide two values in c#?

I want get integer quotient when I divide two values. Per example
X=3
Y=2
Q=X/Y = 1.5 // I want get 1 from results
X=7
Y=2
Q=X/Y=3.5 //I want get only 3 from results
Integer math is going to do this for you.
int x = 3 / 2; // x will be 1
int y = 7 / 2; // y will be 3
int z = 7 % 2; // z will be 1
If you were using decimal or floating-point values in your equations, that would be different. The simplest answer is to cast the result to an int, but there are static Math functions you could also use.
double a = 11d;
double b = 2d;
int c = (int)(a / b); // showing explicit cast, c will be 5
Try Math.Truncate. This should do it.
In VB.NET there is the integer division operator (\). It returns only the integer portion of the division. This comes all the way from the original Dartmouth BASIC so it exists in most forms of BASIC.
try Math.Floor()
There is another elegant way of getting quotient and remainder in .NET using Math.DivRem() method which takes 2 input parameter, 1 output parameter and returns integer.
using System;
For dividend: 7 and divisor: 2
To get only quotient(q)
int q = Math.DivRem(7, 2, _);
//requires C# >= 7.0 to use Discards( _ )
To get quotient(q) and remainder(r)
int q = Math.DivRem(7, 2, out int r);
Math.DivRem() has 2 overloads for 32-bit and 64-bit signed integers.
try using simple maths
int X = 10 ;
int Y = 3 ;
int Q = ( X - ( X % Y ) ) / Y ; // ( it will give you the correct answer )
It works by subtracting the remainder beforehand from the first number so that we don't get a remainder at all !

Nth root of small number return an unexpected result in C#

When I try to take the N th root of a small number using C# I get a wrong number.
For example, when I try to take the third root of 1.07, I get 1, which is clearly not true.
Here is the exact code I am using to get the third root.
MessageBox.Show(Math.Pow(1.07,(1/3)).toString());
How do I solve this problem?
I would guess that this is a floating point arithmetic issue, but I don't know how to handle it.
C# is treating the 1 and the 3 as integers, you need to do the following:
Math.Pow(1.07,(1d/3d))
or
Math.Pow(1.07,(1.0/3.0))
It is actually interesting because the implicit widening conversion makes you make a mistake.
I'm pretty sure the "exact code" you give doesn't compile.
MessageBox.Show(Math.Pow(1.07,(1/3).toString()));
The call to toString is at the wrong nesting level, needs to be ToString, and (1/3) is integer division, which is probably the real problem you're having. (1/3) is 0 and anything to the zeroth power is 1. You need to use (1.0/3.0) or (1d/3d) or ...
First things first: if that's the exact code you're using, there's likely something wrong with your compiler :-)
MessageBox.Show(Math.Pow(1.07,(1/3).toString()));
will evaluate (1/3).toString() first then try and raise 1.07 to the power of that string.
I think you mean:
MessageBox.Show(Math.Pow(1.07,(1/3)).ToString());
As to the problem, (1/3) is being treated as an integer division returning 0 and n0 is 1 for all values of n.
You need to force it to a floating point division with something like 1.0/3.0.
This may help in case you have a real nth root precision problem, but my experiance is that the builtin Math.Pow(double, int) is more precise:
private static decimal NthRoot(decimal baseValue, int N)
{
if (N == 1)
return baseValue;
decimal deltaX;
decimal x = 1M;
do
{
deltaX = (baseValue / Pow(x, N - 1) - x) / N;
x = x + deltaX;
} while (Math.Abs(deltaX) > 0);
return x;
}
private static decimal Pow(decimal a, int b)
{
if (b == 0) return 1;
if (a == 0) return 0;
if (b == 1) return a;
if (b % 2 == 0)
return Pow(a * a, b / 2);
else if (b % 2 == 1)
return a * Pow(a * a, b / 2);
return 0;
}

Fast way to manually mod a number

I need to be able to calculate (a^b) % c for very large values of a and b (which individually are pushing limit and which cause overflow errors when you try to calculate a^b). For small enough numbers, using the identity (a^b)%c = (a%c)^b%c works, but if c is too large this doesn't really help. I wrote a loop to do the mod operation manually, one a at a time:
private static long no_Overflow_Mod(ulong num_base, ulong num_exponent, ulong mod)
{
long answer = 1;
for (int x = 0; x < num_exponent; x++)
{
answer = (answer * num_base) % mod;
}
return answer;
}
but this takes a very long time. Is there any simple and fast way to do this operation without actually having to take a to the power of b AND without using time-consuming loops? If all else fails, I can make a bool array to represent a huge data type and figure out how to do this with bitwise operators, but there has to be a better way.
I guess you are looking for : http://en.wikipedia.org/wiki/Montgomery_reduction
or the simpler way based on Modular Exponentiation (from wikipedia)
Bignum modpow(Bignum base, Bignum exponent, Bignum modulus) {
Bignum result = 1;
while (exponent > 0) {
if ((exponent & 1) == 1) {
// multiply in this bit's contribution while using modulus to keep result small
result = (result * base) % modulus;
}
// move to the next bit of the exponent, square (and mod) the base accordingly
exponent >>= 1;
base = (base * base) % modulus;
}
return result;
}
Fast Modular Exponentiation (I think that's what it's called) might work.
Given a, b, c and a^b (mod c):
1. Write b as a sum of powers of 2. (If b=72, this is 2^6 + 2^3 )
2. Do:
(1) a^2 (mod c) = a*
(2) (a*)^2 (mod c) = a*
(3) (a*)^2 (mod c) = a*
...
(n) (a*)^2 (mod c) = a*
3. Using the a* from above, multiply the a* for the powers of 2 you identified. For example:
b = 72, use a* at 3 and a* at 6.
a*(3) x a*(6) (mod c)
4. Do the previous step one multiplication at a time and at the end, you'll have a^b % c.
Now, how you're going to do that with data types, I don't know. As long as your datatype can support c^2, i think you'll be fine.
If using strings, just create string versions of add, subtract, and multiply (not too hard). This method should be quick enough doing that. (and you can start step 1 by a mod c so that a is never greater than c).
EDIT: Oh look, a wiki page on Modular Exponentiation.
Here's an example of Fast Modular Exponentiation (suggested in one of the earlier answers) in java. Shouldn't be too hard to convert that to C#
http://www.math.umn.edu/~garrett/crypto/a01/FastPow.html
and the source...
http://www.math.umn.edu/~garrett/crypto/a01/FastPow.java
Python has pow(a,b,c) which returns (a**b)%c (only faster), so there must be some clever way to do this. Maybe they just do the identity you mentioned.
I'd recommend checking over the Decimal documentation and seeing if it meets your requirements since it is a built in type and can use the mod operator. If not then you're going to need an arbitrary precision library like java's Bignum.
You can try factoring 'a' into sufficiently small numbers.
If the factors of 'a' are 'x', 'y', and 'z', then
a^b = (x^b)(y^b)(z^b).
Then you can use your identity: (a^b)%c = (a%c)^b%c
It seems to me like there's some kind of relation between power and mod. Power is just repeated multiplication and mod is related to division. We know that multiplication and division are inverses, so through that connection I would assume there's a correlation between power and mod.
For example, take powers of 5:
5 % 4 = 1
25 % 4 = 1
125 % 4 = 1
625 % 4 = 1
...
The pattern is clear that 5 ^ b % 4 = 1 for all values of b.
It's less clear in this situation:
5 % 3 = 2
25 % 3 = 1
125 % 3 = 2
625 % 3 = 1
3125 % 3 = 2
15625 % 3 = 1
78125 % 3 = 2
...
But there's still a pattern.
If you could work out the math behind the patterns, I wouldn't be surprised if you could figure out the value of the mod without doing the actual power.
You could try this:
C#: Doing a modulus (mod) operation on a very large number (> Int64.MaxValue)
http://www.del337ed.com/blog/index.php/2009/02/04/c-doing-a-modulus-mod-operation-on-a-very-large-number-int64maxvalue/
Short of writing your own fast modular exponentiation, the simplest idea I can come up with, is to use the F# BigInt type: Microsoft.FSharp.Math.Types.BigInt which supports operations with arbitrarily large scale - including exponentiation and modular arithmetic.
It's a built-in type that will be part of the full .NET framework with the next release. You don't need to use F# to use BitInt - you can make use of it directly in C#.
Can you factor a, b, or c? Does C have a known range?
These are 32 bit integers! Go check this site
For instance, here is how you get the mod of n%d where d 1>>s (1,2,4,8,...)
int n = 137; // numerator
int d = 32; // denom d will be one of: 1, 2, 4, 8, 16, 32, ...
int m; // m will be n % d
m = n & (d - 1);
There is code for n%d where d is 1>>s - 1 (1, 3, 7, 15, 31, ...)
This is only going to really help if c is small though, like you said.
Looks like homework in cryptography.
Hint: check out Fermat's little theorem.

Categories

Resources