Solving project euler number 6 in C# [closed] - c#

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I am trying to solve the Project Euler problem number 6 with the following program:
double counter = 1;
double sumsquare = 0;
double squaresum = 0;
while (counter <= 100)
{
sumsquare += Math.Pow(counter, 2);
squaresum += counter;
counter++;
}
Math.Pow(squaresum, 2);
Console.WriteLine("the sum is {0} ,the square is :{1}", squaresum.ToString(), sumsquare.ToString());
double diff = sumsquare - squaresum;
Console.WriteLine(diff.ToString());
Console.ReadLine();
However, the answer was wrong. Can anyone tell me what the problem is with my code?

You have an error in that you are computing a power and then discarding it.
More generally, you should avoid double when solving PE problems that involve integers. Doubles are only accurate to fifteen decimal places; after that, they round off.
Better types to use are long, which can represent integers up to 9,223,372,036,854,775,807 or decimal, which can represent integers up to 79,228,162,514,264,337,593,543,950,335, or BigInteger, which can represent arbitrarily large values.
Note that code typically gets slower as you use the larger and larger types.
Even more generally, now would be a good time to learn how to use a debugger. Figure out what the output of your program should be for a very small case that you can calculate by hand. Then step through your program line by line and see where it goes wrong. That is a far more efficient way to debug a problem than asking the internet.

You seem to think that Math.Pow(squaresum, 2); modifies squaresum. That's not so: it returns a square of squaresum, and you should assign it to squaresum if you want the variable to be modified.
squaresum = Math.Pow(squaresum, 2);
Also the idea of using double type here is not quite good, but it appears that you won't lose enough precision here to get a wrong result.

Related

Multiplication of two 64 digit nos [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
How can I multiply two 64 digit decimal numbers together in C# without overflowing?
If you need 64 decimal digit numbers, and if they are integers, you can use System.Numerics.BigInteger struct (needs a reference to System.Numerics.dll assembly).
BigInteger firstNumber = BigInteger.Parse("63518439492097324687235465876298368764576527346564625480");
BigInteger secondNumber = BigInteger.Parse("84890247648975285765484902890273086475254764765147643611");
BigInteger product = firstNumber * secondNumber;
You could always use decimal to store the result of multiplication of two long numbers.
long bigNumber = 12345678L;
long anotherBigNumber = 23456789L;
decimal result = bigNumber * anotherBigNumber;
I think you can do the calculation of any number (as long as you want to) IF first that number you convert into string (so two separate string) than get the last number (character) and multiply it with every number from the other character (just like you learned in school) and so on and you add that to you final score number (also as a string). I know this can be done and it would be king difficult logic at the beginning but once you create this function you can multiply any number you want :)
If they are integers, use the BigInteger class in System.Numerics (Reference System.Numerics.dll!)
If not, there is a BigRational class in Codeplex. It was meant to be in System.Numerics but it got kicked. Link:
http://bcl.codeplex.com/releases/view/42782

strange issue with double.parse conversion [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
Im using visual studio 2010, windows form.
I have this code, that permit to convert money from USD to EUR. This is reference: http://www.codeproject.com/Articles/17909/Simple-Class-to-get-Currency-Exchange-Rates
This is code:
CurrencyConverter2 cc = new CurrencyConverter2();
cc.AdjustToLocalTime = true;
CurrencyData cd = new CurrencyData("USD", "EUR");
// Convert US Dollars to Euros
cc.GetCurrencyData(ref cd);
label5.Text = (5000 / cd.Rate).ToString();
OUTPUT IN THIS CASE IS : 3753,75375375375
But if I place value (example 5000) from texbox in this way:
double cambiamo = double.Parse(tbxDaConvertire.Text);
tbxConvertito.Text = (cambiamo * cd.Rate).ToString();
OUTPUT IS: 3752,5
I dont understand because Im getting this value!
How can I solve it please?
As comments have pointed out:
double cdRate = 1.42f;
var value1 = (5000 / cdRate).ToString();
var value2 = (double.Parse("5000") / cdRate).ToString();
var value3 = (5000.0f / cdRate).ToString();
// value1 = "3521.12686697913"
// value2 = "3521.12686697913"
// value3 = "3521.12686697913"
It is most likely that your CD rate is different. For a start in your first example you use 5000 / cd.Rate and in your second you use 5000 * cd.Rate - have you at some time performed cd.Rate = 1/cd.Rate? That could be where the discrepancy is arising.
Your first conversion used a conversion rate of 0.75075
Your second conversion used a conversion rate of 0.75050
Just a 0.00025 difference, easily found back in this chart of the conversion rate of the past week:
Note the extreme volatility, the rate changes in minutes. Or to put it another way, it changed while you edited your code. Clearly you are getting live updates from your currency conversion service.

What is the lightest collection for store these values? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I have many objects (such as 10.000, more or less). Every object has3 values :
Index (decimal, such as 0,0 <= X <= 100.000,9);
A Latitude value;
A Longitude value;
and I need to perform some search due to the Index value. Which will be the light approch to this? List<MyObject>? I know there are hashtable, but only for 2 values...
I read these values from a .csv file and I'll store it on application. WebForm, .NET 4.5.
The very lightest approach in terms of memory use is to put these into a struct, and hold them in an array of such structs. From what you say, you can't really pack data any tighter than that: two doubles and a decimal will occupy 32 bytes per entry, and the array of structs does not add any per-item overhead on top of this.
Having said that, this will slow down your coding and might save too little to matter in practice.
Why don't you use a Dictionary like this:
public class Position
{
public Latitude Latitude { get ; set ; }
public Longitude Longitude { get ; set ; }
}
public Dictionary<decimal,Position> Positions ;
Or use a Tuple in the dictionary:
public Dictionary<decimal,Tuple<Latitude,Longitude>> Positions ;
I believe the absolutely lightest approach would be bitmasking your values into an unsigned long, though it is slightly cumbersome.
To really get the grasp on which is the most efficient approach, i recommend trying them all with test values and looking at the output of sizeof() on them. that way you'd be really sure what's their runtime memory size.
I'd suggest a custom struct to hold your values, a tuple could work as well.

Array containing only 0 and 1 values [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I need an array which will only contain the values 0 and 1. Will bool[] be good enough for me? Or is there something lighter weight?
EDIT:
I dont have memory constraints but that array is made and passes online All The Time with big files passes concurrently with that array. I want the maximun optimization so the big files wont be delayed
A bool is probably not the best way to do it. Depends how many numbers you have got.
It is important to realise that even though a bool is a single bit, it requires a full byte in memory.
A BitArray on the other hand takes care of this for you and is more space efficient, although ever so slightly less time efficient.
http://msdn.microsoft.com/en-us/library/system.collections.bitarray.aspx
Depends on your constraints, if it is not for a constrained environment a bool array will work just fine.
Bool Array is good enough. You can consider "false" as 0 and "true" as 1.
May be you need BitArray, the sequence of 1 and 0.
bool[] would do the trick... If your 0 & 1 numbers are in fact just "Flags" and not real numbers.
Using an Enum with the Flags attribute is another option. This would allow you to have an Intention Revealing Name for both boolean values.
[Flags()]
public enum TheFlags
{
NoneSet = 0,
FirstSet = 1,
SecondSet = 2
}
Then you can check if "First" is set like so:
TheFlags flags = TheFlags.FirstSet;
if (flags.HasFlag(TheFlags.FirstSet))
Console.WriteLine("First flag is set!");

C# code or algorithm to quickly calculate distance between large strings? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
Hi and thanks for looking!
Background
I have an XML file that contains 1900 nodes which themselves contain a string of encoded data of about 3400 characters.
As part of a use case for an application I am developing, I need to be able to take a "benchmark" string at runtime, and find the closest match from the XML file.
Please note that XML is not germane to the app and that I may go with SQL moving forward, but for today, I just needed an easy place to store the data and prove the concept.
I am using .NET 4.0, C#, forms app, LINQ, etc.
Question
How do I find the closest match? Hamming? Levenshtein? There are plenty of code samples online, but most are geared towards small string comparisons ("ant" vs. "aunt") or exact match. I will rarely have exact matches; I just need closest match.
Thanks in advance!
Matt
You mentioned using Levenhstein's Edit Distance and that your strings were about 3400 characters long.
I did a quick try and using the dynamic programming version of Levenhstein's Edit Distance it seems to be quite fast and cause no issue.
I did this:
final StringBuilder sb1 = new StringBuilder();
final StringBuilder sb2 = new StringBuilder();
final Random r = new Random(42);
final int n = 3400;
for (int i = 0; i < n; i++) {
sb1.append( (char) ('a' + r.nextInt(26)) );
sb2.append( (char) ('a' + r.nextInt(26)) );
}
final long t0 = System.currentTimeMillis();
System.out.println("LED: " + getLevenshteinDistance(sb1.toString(), sb2.toString()) );
final long te = System.currentTimeMillis() - t0;
System.out.println("Took: " + te + " ms");
And it's finding the distance in 215 ms on a Core 2 Duo from 2006 or so.
Would that work for you?
(btw I'm not sure I can paste the code for the DP LED implementation I've got here so you probably should search the Internet for one Java implementation)

Categories