|
It is not important for me to know the answer.
I want to find out the best algorithm, and you are not going to help me.
Thanks anyway.
Meysam
|
|
|
|
|
Meysam Tolouee wrote: nd you are not going to help me.
What the hell do you want him to do ? He has told you in about every possible way how you should improve your code, starting by implementing the algorithm correctly.
~RaGE();
I think words like 'destiny' are a way of trying to find order where none exists. - Christian Graus
Do not feed the troll ! - Common proverb
|
|
|
|
|
We have told you where the algorithm is. You just haven't used it. Seriously, put your preconceptions to one side and take a look at that wiki page. Read the explanation and then carefully read the algorithm presented there. Then try writing it fresh. You'll be amazed at the difference.
|
|
|
|
|
You made a big error in the algorithm as stated above. Also you add work with instantiating classes (struct probably better).
private static bool[] _numbers;
static void Main(string[] args)
{
var sw = new Stopwatch();
sw.Start();
Run();
sw.Stop();
Console.WriteLine("Milliseconds run: " + sw.ElapsedMilliseconds);
Console.WriteLine("Primes: " + _numbers.Count(i => i));
Console.ReadLine();
}
private static void Run()
{
const int count = 2000000;
_numbers = new bool[count];
for (int i = 2; i < count; i++)
_numbers[i] = true;
int baseCounter = 1;
while (baseCounter < count)
{
do
{
baseCounter++;
if (baseCounter == count) return;
} while (!_numbers[baseCounter]);
int counter = baseCounter << 1;
while (counter < count)
{
_numbers[counter] = false;
counter += baseCounter;
}
}
|
|
|
|
|
I want the sum of prime numbers not count of them!
long sum = 0;
for (int i = 0; i < _numbers.Length - 1; i++)
{
if (_numbers[i])
sum += i;
}
Thank you for your time.
Meysam
modified 12-Sep-12 17:12pm.
|
|
|
|
|
If you want the sum or primes then:
static void Main(string[] args)
{
var sw = new Stopwatch();
sw.Start();
Run();
sw.Stop();
Console.WriteLine("Milliseconds run: " + sw.ElapsedMilliseconds);
Console.WriteLine("Primes: " + _numbers.Count(i => i));
var sum = 0;
for (int i = 2; i < _numbers.Count(); i++)
if (_numbers[i]) sum += i;
Console.WriteLine("Sum of Primes: " + sum.ToString("n0"));
Console.ReadLine();
}
|
|
|
|
|
Wow. With all this talk of Project Euler #10, I had to go dig up my answer to the problem from a couple of years ago. My implementation get the answer in 71 milliseconds, but I had mine built into a class and used tristates instead of booleans.
[EDIT]
Whoops. Might help if I wrap the stop watch around the code that generates the data and not include the code the sums up all the values. And it might help if I ran the Release version instead of the Debug.
New time: 17 milliseconds
modified 12-Sep-12 18:52pm.
|
|
|
|
|
Amazing, is it not. The questioner totally screwed up the algorithm, doing it the brut force way. Obviously took forever. Did not even realize was not doing the algorithm. Mine is not even optimal, made a slight change and got down to 24 ms.
|
|
|
|
|
Yeah, some people shouldn't ask questions if they are going to deny every person giving them every correct answer.
|
|
|
|
|
This is an article about finding prime numbers using the Sieve of Eratosthenes:
Finding prime numbers[^]
It's in VB.NET, but you can download the source in C#.
|
|
|
|
|
There are references to a pure C# implementation that sovles his problem completely there as well.
|
|
|
|
|
I don't think I've ever seen it done so inefficiently.
0) You don't need to store the value; use the index.
1) You don't need to allocate space for even numbers.
2) You don't need to allocate a boolean (8-bit) just to store one bit worth of information.
3) You don't need to investigate the whole range; only investigate up to the square root (as others have already told you), then simply iterate the rest.
|
|
|
|
|
Hi All, I am looking at a tutorial on using Gridview and the Hyperlinkfield, and I have question that I'd like to have an answer to. The tutorial I'm looking at is the article Practical Guide for Creating HyperLinkField in GridView in ASP.NET. In it, the author uses a gridview to display a student's information in four columns namely UserID, UserName, FilePath, and Photo. The FilePath column is what I'm interested in, when users click on links inside of it they can download students' profiles which are stored on the web server. The links are full paths to the profiles stored on the database. How do I modify the the code so that instead of seeing the full paths of files, all the users see are their names, and on top of that still enable users to download the profiles by clicking on the file names? Thanks in advance for your help.
|
|
|
|
|
Shouldn't you be asking this on that article instead?
|
|
|
|
|
The article is quite old, I did not see any new activities lik questions being asked so I thought it wasn't active.
|
|
|
|
|
I want to get the name of the printer chosen in Acrobat PrintDialog using SendMessage Windows API.
This is sample code.
static string GetWindowText( hwnd_printDialog_in_Acrobat )
{
int comboBoxCount = 0;
int HWND_PRINTER_NAME = 1 ;
List<intptr> ChildPtrList = GetChildWindows(hwnd_printDialog_in_Acrobat);
for( i=0 ; i < ChildPtrList.Size(); i++) {
GetClassName( ChildPtrList[i], sClass, 100);
if (sClass.ToString() == "ComboBox") {
comboBoxCount++;
if (comboBoxCount == HWND_PRINTER_NAME ) {
hwnd = ChildPtrList[i];
break;
}
}
}
ChildPtrList.Clear();
int sSize ;
sSize = SendMessageW( hwnd, WM_GETTEXTLENGTH, IntPtr.Zero, IntPtr.Zero )+1;
StringBuilder sbTitle = new StringBuilder( sSize );
SendMessageW( hwn, WM_GETTEXT, (IntPtr)sSize, sbTitle);
return (sbTitle.ToString());
}
The return value of sSize is 4; The value of sbTitle.ToString() is "?-" etc.
The expected result what I want is "HP Officejet Pro .. ", for example.
What is wrong?
Thanks in advnace.
|
|
|
|
|
toBeH_S wrote: SendMessageW( hwn, WM_GETTEXT, (IntPtr)sSize, sbTitle);
You probably meant hwnd.
What is the following code doing:
StringBuilder title = new StringBuilder();
Int32 sSize = SendMessage((int)hWnd, WM_GETTEXTLENGTH, 0, 0).ToInt32();
if (sSize > 0)
{
sbTitle = new StringBuilder(sSize + 1);
SendMessage(hwnd,( int)WM_GETTEXT, sbTitle.Capacity, sbTitle);
}
return sbTitle.ToString();
There could also be a Unicode problem.
~RaGE();
I think words like 'destiny' are a way of trying to find order where none exists. - Christian Graus
Do not feed the troll ! - Common proverb
|
|
|
|
|
Rage wrote: What is the following code doing:
StringBuilder title = new StringBuilder();
Int32 sSize = SendMessage((int)hWnd, WM_GETTEXTLENGTH, 0, 0).ToInt32();
if (sSize > 0)
{
sbTitle = new StringBuilder(sSize + 1);
SendMessage(hwnd,( int)WM_GETTEXT, sbTitle.Capacity, sbTitle);
}
return sbTitle.ToString();
1. The above code retrieves the name of the printer chosen from the printer name combobox in printDialog.
hwnd : handle of the printer name combobox in PrintDialog of Acrobat.
1) Firstly, get the length of the printer name.
int sSize=SendMessage((int)hwnd, WM_GETTEXTLENGTH, 0,0),ToInt32();
2) Secondly, memory allocation for the name of the printer.
sbTitle = new StringBuilder( sSize + 1);
3) Finally, retrieve the name of the printer using SendMessage Windows API.
SendMessage(hwnd, (int)WM_GETTEXT, sbTitle.Capacity, sbTitle);
What I want is to retrieve the name of the printer chosen in acrobat printDialog from another application via SendMessage.
2.
Rage wrote: There could also be a Unicode problem.
Maybe you right.
The original version is as follows:
if ( isWindowUnicode(hwnd)) {
StringBuilder title = new StringBuilder();
Int32 sSize = SendMessageW((int)hWnd, WM_GETTEXTLENGTH, 0, 0).ToInt32();
if (sSize > 0)
{
sbTitle = new StringBuilder(sSize + 1);
SendMessageW(hwnd,( int)WM_GETTEXT, sbTitle.Capacity, sbTitle);
}
return sbTitle.ToString();
}
|
|
|
|
|
toBeH_S wrote: What is the following code doing:
With that statement I was actually trying to ask you to try the code I have put in my post: it is very similar to yours, with a few more tests to check the size (and hence check if the GETTEXTLENGTH is working) and some safer practices.
~RaGE();
I think words like 'destiny' are a way of trying to find order where none exists. - Christian Graus
Do not feed the troll ! - Common proverb
|
|
|
|
|
I'm so sorry several days I can't come back.
I have several urgent jobs and my program runs abnormally, so I tried to fix them.
I apologize my being away from your advise.
|
|
|
|
|
I would like to create an extension method that randomly permutes the contents of an ordered list (preferably in-place). This is what I have so far:
public static class PermuteExtensions {
public void Permute<T, U>(this T list) where T : IEnumerable<U> {
U[] tempArray = list.ToArray();
long arraySize = tempArray.LongLength;
long[] indexes = new long[arraySize];
long j = 0;
IEnumerator<U> enumer = list.GetEnumerator();
while (enumer.GetNext()) {
enumer.Current = tempArray[indexes[j++]];
}
}
} There are two problems with this approach:
1. I cannot figure out how to modify the contents of an IEnumerable object.
2. How to specify the constraint on T such that I allow this method to be called on the ordered collections (IList, Stack, Queue, List, LinkedList), but not on the unordered collections (IDictionary, Dictionary, ISet, Set).
It is NOT a firm requirement that this be an in-place algorithm. However, I don't know how to construct a new T object that offers a consistent way to add objects for all of the ordered collections listed above. Thanks,
Sounds like somebody's got a case of the Mondays
-Jeff
|
|
|
|
|
You're trying to modify a collection through the IEnumerable interface. This is something you are expressly forbidden to do as modifying the target of an enumerator invalidates the state of the enumerator.
Since each of these ordered collections is a different implementation, and only has the IEnumerable interface in common, I don't think there is an extension solution.
I think you would have to create new versions of these ordered collection types, inheriting from them so you can manipulate the underlying structures and still maintain the business rules of the parent class. For instance, a List collection, internally, works a bit differently from a Stack and works very differently from LinkedList. Each is going to have to have it's own wrapper implementation.
But, why would you even want to randomly rearrange the objects in a Stack or a LinkedList anyway? I see no productive reason to do so.
|
|
|
|
|
 I find this an interesting programming problem, even though I wonder, like Dave K., why you'd want to do this (gambling program, card game shuffle and deal).
But, if someone with the intelligence, and skill, of Dave K. says this cannot be done as an extension, and that you will need to have wrappers for each of your Types you wish to "permutate:" I'd accept his opinion, and pursue his suggestions, if you must do this.
However, that doesn't stop me, out of curiousity, just starting to see how this might be done (but, not as an extension).
Here's some code I started, and will not have time to work-on further for a while, but perhaps it will be useful to you in some way:
// Visual Studio 2012 RC
// Framework 4.5
// WinForms: one Form with one Button it named 'Permute
//
// build a List of Types to permute
private static List<Type> OkayCollectionTypes = new List<Type>()
{
typeof(List<>),
typeof(Stack),
typeof(Queue),
typeof(LinkedList<>)
};
// create some samples to play with
private static List<int> IntList = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
private static Stack AStack = new Stack(IntList as IList);
// test stub for Permute function
private static dynamic Permute(dynamic permuteTarget)
{
Type currentType = permuteTarget.GetType();
// Note: we cannot use Type.GetType() here
// an error will be thrown
// see comments in the BtnPermuteClick EventHandler
if(OkayCollectionTypes.Contains(currentType))
{
MessageBox.Show("okay : Type = " + permuteTarget.ToString());
}
else
{
return null;
}
// at this point we create a new instance
// of 'permuteTarget that we permutate ?
// to be explored ...
return (permuteTarget);
}
private void BtnPermuteClick(object sender, EventArgs e)
{
// this works
// although it has no effect on AStack's contents
AStack = Permute(AStack);
// this will not work
// because the type of IntList is:
// System.Collections
// .Generic.List`1
// [
//[System.Int32,
// ... snip ...
//PublicKeyToken=b77a5c561934e089]
// ]
// if we tried to use Type.GetType() in the Permute method
// an error would be thrown like this:
//'System.Collections.Generic.List<int>' does not contain a definition for 'Type'
// var mutatedList = Permute(IntList);
} Obvious questions to be explored:
0. is using 'dynamic here the source of all problems ?
1. is the problem with trying use the 'Permute method on 'IntList here created by the fact that I am using direct assignment to create the contents of 'IntList, thus making its contents not usable for some reason ?
No, it is not, because initializing IntList in a for loop using 'Add: the Type of the dynamic parameter in the Permute method will look like this when examined at run-time using the Command window after reaching a break-point:
> ? currentType is IList
false
> ? currentType is List<int>
false
* the following edited for brevity
> ? currentType.GetType()
{Name = "RuntimeType" FullName = "System.RuntimeType"}
[System.RuntimeType]: {Name = "RuntimeType" FullName = "System.RuntimeType"}
base {System.Reflection.MemberInfo}: {Name = "RuntimeType" FullName = "System.RuntimeType"}
AssemblyQualifiedName: "System.RuntimeType, ... snip ... PublicKeyToken=b77a5c561934e089"
BaseType: {Name = "TypeInfo" FullName =
GenericParameterPosition: 'currentType.GetType().GenericParameterPosition' threw an exception of type 'System.InvalidOperationException'
GenericTypeArguments: {System.Type[0]}
GUID: {97e69551-7329-39c5-ba61-2ca4b573e0e5}
IsClass: true
IsGenericType: false
UnderlyingSystemType: {Name = "RuntimeType" FullName = "System.RuntimeType"} Out of time: now.
best, Bill
<color>"When it comes to atoms, language can be used only as in poetry. The poet, too, is not nearly so concerned with describing facts as with creating images." Niels Bohr
|
|
|
|
|
Skippums wrote: 1. I cannot figure out how to modify the contents of an IEnumerable object.
As you've discovered, you can't change the object you're enumerating over because you'd invalidate the enumerator. What you could do, though, is not use the enumerator - instead, you can iterate over the collection by index using a for loop, and update the underlying array using that instead. So, your loop becomes something like:
for (int i = 0; i < list.Count; i++)
{
list[i] = tempArray[indexes[j++]];
} Note that this isn't possible for something like a LinkedList .
As for the constraint - I'm afraid that you can't do this at the constraint level. You'd have to test this in the actual method body and raise an exception if it was the wrong type.
modified 12-Sep-12 7:28am.
|
|
|
|
|
Pete O'Hanlon wrote: Note that this isn't possible for something like a LinkedList .
This is exactly why I said he'd have to wrap each collection he wanted to do this to.
|
|
|
|
|