Can I declare constant integers with a thousands separator in C#? - c#

The Cobra programming language has a useful feature where you can use underscores in numeric literals to improve readability. For example, the following are equivalent, but the second line is easier to read:
x = 1000000
x = 1_000_000 # obviously 1 million
Is there anything equivalent for C#?

Answer as of C# 7
Yes, this is supported in C# 7. But be aware that there's no validation that you've put the underscores in the right place:
// At a glance, this may look like a billion, but we accidentally missed a 0.
int x = 1_00_000_000;
Answer from 2011
No, there's nothing like that in C#. You could do:
const int x = 1000 * 1000;
but that's about as nice as it gets.
(Note that this enhancement went into Java 7 as well... maybe one day it will be introduced in C#.)

Yes you can do this with C # 7.0 as shown here
public const long BillionsAndBillions = 100_000_000_000;

Related

c# - What does binary representation of uint is like?

I'm trying to solve a simple question on leetcode.com (https://leetcode.com/problems/number-of-1-bits/) and I encounter a strange behavior which is probably my lack of understanding...
My solution to the question in the link is the following:
public int HammingWeight(uint n) {
int sum = 0;
while (n > 0) {
uint t = n % 10;
sum += t == 0 ? 0 : 1;
n /= 10;
}
return sum;
}
My solution was to isolate each number and if it's one increase the sum. When I ran this on my PC it worked (yes - I know it's not the optimal solution and there are more elegant solutions considering it's binary representation).
But when I tried running in the leetcode editor it returned a wrong answer for the following input (00000000000000000000000000001011).
No real easy way to debug other then printing to the console so I printed the value of n when entering the method and got the result of 11 instead of 1011 - on my PC I got 11. If I take a different solution - one that uses bitwise right shift or calculating mod by 2 then it works even when the printed n is still 11. And I would have expected those solutions to fail as well considering that n is "wrong" (different from my PC and the site as described).
Am I missing some knowledge regarding the representation of uint? Or binary number in a uint variable?
Your code appears to be processing it as base 10 (decimal), but hamming weight is about base 2 (i.e. binary). So: instead if doing % 10 and /= 10, you should be looking at % 2 and /= 2.
As for what uint looks like as binary: essentially like this, but ... the CPU is allowed to lie about where each of the octets actually is (aka "endianness"). The good news is: it doesn't usually expose that lie to you unless you cheat and look under the covers by looking at raw memory. As long as you use regular operators (include bitwise operators): the lie will remain undiscovered.
Side note: for binary work that is about checking a bit and shuffling the data down, & 1 and >> 1 would usually be preferable to % 2 and / 2. But as canton7 notes: there are also inbuilt operations for this specific scenario which uses the CPU intrinsic instruction when possible (however: using the built-in function doesn't help you increase your understanding!).
This Kata has a poor writing, in the examples the Inputs are printed in binary representation while the Outputs are in printed in decimal representation. And there is no clues to help understand that.
00000000000000000000000000001011b is 11 (in decimal, 8 + 2 + 1). That is why you get 11 as input for the first test case.
There is no numbers made of 0s and 1s in base 10 you have to decode as base 2 stuff here.
To solve the Kata, you just need to work in base 2 as you succeed to do and like #MarcGravell explained.
Please check below code, it will work for you.
Its very simple way to solve.
var result = 0;
for(var i = 0; i < 32; i++)
{
if ((n & 1) == 1) result++;
n = n >> 1;
}
return result;

Treat all numeric literals as doubles

Is there any way in C# to treat all numeric literals (which I describe as "magic numbers") as doubles?
For example
double number = 1;
var a = 7 / 8 * number;
In this calculation 7 / 8 returns 0, but 7.0 / 8.0 returns 0.875.
In my case most of these formulas are copied from VBA and they are all over the place. It would be very time consuming and error prone to find all of them and replace them manually.
There is no global setting, code must be updated. The method I used is posted in the answer of this question.
Visual Studio replace magic number integers with doubles

Get last (ie endswith) 3 digits of a decimal (.NET)

I may be using Math for evil... But, in a number written as 0.7000123
I need to get the "123" - That is, I need to extract the last 3 digits in the decimal portion of a number. The least significant digits, when the first few are what most people require.
Examples:
0.7500123 -> 123
0.5150111 -> 111
It always starts from digit 5. And yes, I'm storing secret information inside this number, in the part of the decimal that will not affect how the number is used - which is the potentially evil part. But it's still the best way around a certain problem I have.
I'm wondering whether math or string manipulation is the least dodgy way of doing this.
Performance is not an issue, at all, since I'm calling it once.
Can anyone see an easy mathematical way of doing this? eg A combination of Math functions (I've missed) in .NET?
It's a strange request to be sure. But one way to get an int value of the last 3 digits is like so:
int x = (int)((yourNumber * 10000000) % 1000);
I'm going to guess there's a better way to get the information you're looking for that's cleaner, but given what you've asked for, this should work.
First Convert Your number into the String.
string s = num.ToString();
string s1 = s.Substring(s.Length - 3, 3);
Now s1 Contains Last 3 Digits Of the Number
Using modulo will get you the last 3 digits:
var d = 0.7000123m;
d = d * 10000000 % 1000;
d will now hold the value 123.
Try this:
string value= "0.1234567";
string lastthreedigit= value.Substring(value.Length - 3);

A value larger than ULong? Computing 100!

I'm trying to compute 100! and there doesn't seem to be a built-in factorial function. So, I've written:
Protected Sub ComputeFactorial(ByVal n As ULong)
Dim factorial As ULong = 1
Dim i As Integer
For i = 1 To n
factorial = factorial * i
Next
lblAnswer.Text = factorial
End Sub
Unfortunately, running this with the value of 100 for n rseults in
Value was either too large or too
small for a UInt64.
So, is there a larger data type for holding numbers? Am i mistaken in my methods? Am I helpless?
Sounds like Project Euler.
.NET 4.0 has System.Numerics.BigInteger, or you can pick up a pretty sweet implementation here:
C# BigInteger Class
Edit: treed :(
I'll add - the version at CodeProject has additional features like integer square root, a primality test, Lucas sequence generation. Also, you don't have direct access to the buffer in the .NET implementation which was annoying for a couple things I was trying.
Until you can use System.Numerics.BigInteger you are going to be stuck using a non-Microsoft implementation like BigInteger on Code Project.
Hint: use an array to store the digits of the number. You can tell by inspection that the result will not have more than 200 digits.
You need an implementation of "BigNums". These are integers that dynamically allocate memory so that they can hold their value.
A version was actually cut from the BCL.
The J# library has an implementation of java.math.BigInteger that you can use from any language.
Alternatively, if precision/accuracy are not a concern (you only care about order of magnitude), you can just use 64-bit floats.
decimal will handle 0 through +/-79,228,162,514,264,337,593,543,950,335 with no decimal point(scale of zero)

High precision integer math in C#?

I have a very large number I need to calculate, and none of the inbuilt datatypes in C# can handle such a large number.
Basicly I want to solve this:
Project Euler 16:
2^15 = 32768 and the sum of its digits
is 3 + 2 + 7 + 6 + 8 = 26.
What is the sum of the digits of the
number 2^1000?
I have already written the code, but, as said before, the number is too large for c# datatypes. The code has been tested and verified with small numbers (such as 2^15) and it works perfectly.
using System;
namespace _16_2E1000
{
class Program
{
static void Main(string[] args)
{
ulong sum = 0;
ulong i = 1 << 1000;
string s = i.ToString();
foreach (char c in s)
{
sum += (ulong) Convert.ToInt64(c.ToString());
}
Console.WriteLine(sum);
Console.ReadLine();
}
}
}
You can use BigInteger from the J# classes. First question in this article tells you how. It's a bit of pain b/c then you have to provide the J# redistributable when you roll out tho.
First to answerer you exact question, look for a BigInt or BigNum type
Second, from what I know of Project Euler, there will be a cool, tricky way to do it that is much easier.
As a first guess I'd compute the answerer for 2^1 -> 2^n (for whatever n you can get to work) and look for patterns. Also look for patterns in the sequences
V(0) = 2^p
V(n) = floor(V(n - 1) / 10)
D(n) = V(n) % 10
I hope this is not a homework problem, but to get to the answer of 2^1000, you'll have to divide it into smaller chunks,
try something like,
2^1000 = 2 * 2^999 = 2^999 + 2^999 = 2^ 998 + 2^ 998 + 2^ 998 + 2^ 998
breaking into smaller bits till you get to solvable a problem,
complete solution to project Euler is on following links.
http://blog.functionalfun.net/2008/07/project-euler-problem-16-calculating.html
http://code.msdn.microsoft.com/projecteuler
It is not necessary to have Big Integer capabilities in order to solve this problem.
One could just use the property that:
2^n = 2^(n-1) + 2^(n-1)
If Big Integer is really necessary for other tasks, I have been using the BigInt class from F# in my C# programs and am happy with it.
The necessary steps:
Install the F# CTP
In your C# (or other .NET language) application add a reference to the FSharp.Core dll.
Add: using Microsoft.FSharp.Math;
In the "Class View" window familiarize yourself with the members of the two classes: BigInt and BigNum
After executing these steps one is basically ready to use the BigInt class.
One last hint:
To avoid declaring variables with improper names to hold constants that makes the code unreadable, I am using a name that starts with _ (underscore), followed by the integer constant. In this way one will have expressions like:
N = _2 * N;
clearly much more readable than:
N = Two * N;
Here's a BigInteger (source code is available) that you can use; though, as already mentioned, there are more efficient ways to do this than brute force.
BigInteger on codeplex
Actually, while a biginteger utility might be of interest here, you don't need it, even for this. Yes, it looks like it does, but you don't. In fact, use of a biginteger form may even slow things down.
Since I don't want to solve the problem for you, I'll just suggest you think about this in a modular way.

Categories

Resources