I'm trying to make a GameClock like a real clock, but with a custom time.
The clock is running but it is delaying and I can't find the problem. Thanks for help.
IEnumerator Start()
{
while (true) {
Sec = DateTime.Now.Second;
if (Hour == 23 && Min == 59 && Sec == 0){
Hour = 0;
Min = 0;
} else if (Min == 59 && Sec == 0){
Min = 0;
Hour += 1;
} else if (Sec == 0) {
Min += 1;
}
yield return new WaitForSeconds (1f);
}
}
i think it should be like
while (true) {
Sec = DateTime.Now.Second;
if (Hour == 23 && Min == 59 && Sec == 59){
Hour = 0;
Min = 0;
} else if (Min == 59 && Sec == 59){
Min = 0;
Hour += 1;
} else if (Sec == 59) {
Min += 1;
}
yield return new WaitForSeconds (1f);
}
I don't get why you are doing all this work when you can just print out easily:
Debug.Log(System.DateTime.Now.ToString("hh:mm:ss"));
Debug.Log(System.DateTime.Now.Hour.ToString());
Debug.Log(System.DateTime.Now.Minute.ToString());
Debug.Log(System.DateTime.Now.Second.ToString());
Related
I'm ripping my hair out on the following so I'm kindly asking for help here.
I have an array of durations in minutes whose total is one day (1440 min.)
I have another array with a value which represent a protection level : 0 to 5.
var levels = new int[3];
levels[0] = 0;
levels[1] = 5;
levels[2] = 0;
var minutes = new int[3];
minutes[0] = 658; // 10 hours and 58 minutes
minutes[1] = 1; // 1 minute
minutes[2] = 781; // 13 hours and 1 minutes
In plain English we should read:
Level 0 duration is 10 hours and 58 minutes, then Level 1 duration is 1 minute and finally we're back to level 0 for 13 hours and 1 minute. End of the day ;)
Of couse this is a simple example, this could be more richer than that, but I hope this helps understand the problem I'm trying to solve which is exposed below.
I need to compute an average of protection level for each hour of the day (from 0 to 23)\
The final result set would be an array of tuples with 6 items
var finalResult = new (int level0percent, int level1percent, int level2percent, int level3percent, int level4percent, int level5percent)[24];
With the data in this example that would mean:
100% for level 0 for Hours from 0 to 9
96% for level 0 for Hour 10
A this point we have 2 minutes left (4%) to be given to Hour 10.
We consume 2% (1 minute) for level 5
Still 2% (1 minute) to consume on the next level, which is 0 for now.
We add 2% (1 minute) to level 0
Then the remaining is now 13 hours for level 0 at index 11 to 23.
The tricky part for me is to process, in this case, the hour at index 10. May be I should restructure the data in a form that would be simplier to process, but I can't figure it out.
Any help appreciated.
PS : If Linq could be of any help, please do not hesitate to use it.
EDIT : Fixed the minutes array.
EDIT 2 : This what I've tried so far...
A level class to hold an intermediary result set:
public class Levels
{
public int level0 { get; set; }
public int level1 { get; set; }
public int level2 { get; set; }
public int level3 { get; set; }
public int level4 { get; set; }
public int level5 { get; set; }
}
The processing code so far... May not compile and/or work:
// Construct the final result to be sent back to the client
var averagesOn24HoursByHourNew = Enumerable.Range(0, 24).Select(i => new Levels()).ToArray();
// This index will allow us to advance each hour of the day (from 0 to 23)
int lastIndexOnAveragesOn24HoursByHourNew = 0;
// Used to gather the remaining minutes for incomplete hours
int lastMinuteLeftOnLastHour = 0;
for (var indexLevel = 0; indexLevel < levels.Count; indexLevel++)
{
if (levels[indexLevel] == 0)
{
int durationInMinutes = (int)minutes[indexLevel];
var nbMinutesLeft = durationInMinutes % 60;
var nbHoursAtOneHundred = durationInMinutes / 60;
if (lastMinuteLeftOnLastHour != 0)
{
averagesOn24HoursByHourNew[lastIndexOnAveragesOn24HoursByHourNew].level0 += lastMinuteLeftOnLastHour * 100 / 60;
nbMinutesLeft -= lastMinuteLeftOnLastHour;
lastMinuteLeftOnLastHour = 0;
}
int index = 0;
for (index = lastIndexOnAveragesOn24HoursByHourNew; index < nbHoursAtOneHundred + lastIndexOnAveragesOn24HoursByHourNew; index++)
{
#if DEBUG
Debug.Assert(index <= 23);
#endif
averagesOn24HoursByHourNew[index].level0 += 100;
datiCountForOneHour[index] += 1;
}
#if DEBUG
// When th whole day is processed the index will be 24
Debug.Assert(index < 25);
#endif
if (nbMinutesLeft != 0)
{
averagesOn24HoursByHourNew[index].level0 += nbMinutesLeft * 100 / 60;
if (lastMinuteLeftOnLastHour != 0 && lastMinuteLeftOnLastHour > nbMinutesLeft)
{
lastMinuteLeftOnLastHour -= nbMinutesLeft;
}
else
{
lastMinuteLeftOnLastHour = 60 - nbMinutesLeft;
}
}
lastIndexOnAveragesOn24HoursByHourNew = index;
}
else if (levels[indexLevel] == 1)
{
int durationInMinutes = (int)minutes[indexLevel];
// A duration of zero means less than one minute
// set it to one minute
if (durationInMinutes == 0)
{
durationInMinutes = 1;
}
else if (durationInMinutes == 1439)
{
// FIXME Add Missing minute if needed
durationInMinutes = 1440;
}
var nbMinutesLeft = durationInMinutes % 60;
var nbHoursAtOneHundred = durationInMinutes / 60;
int index = 0;
for (index = lastIndexOnAveragesOn24HoursByHourNew; index < nbHoursAtOneHundred + lastIndexOnAveragesOn24HoursByHourNew; index++)
{
#if DEBUG
Debug.Assert(index <= 23);
#endif
if (lastMinuteLeftOnLastHour != 0)
{
averagesOn24HoursByHourNew[index].level1 += lastMinuteLeftOnLastHour * 100 / 60;
lastMinuteLeftOnLastHour = 0;
}
else
{
averagesOn24HoursByHourNew[index].level1 += 100;
}
datiCountForOneHour[index] += 1;
}
#if DEBUG
// When th whole day is processed the index will be 24
Debug.Assert(index < 25);
#endif
if (nbMinutesLeft != 0)
{
averagesOn24HoursByHourNew[index].level1 += nbMinutesLeft * 100 / 60;
if (lastMinuteLeftOnLastHour != 0 && lastMinuteLeftOnLastHour > nbMinutesLeft)
{
lastMinuteLeftOnLastHour -= nbMinutesLeft;
}
}
lastIndexOnAveragesOn24HoursByHourNew = index;
}
else if (levels[indexLevel] == 2)
{
int durationInMinutes = (int)minutes[indexLevel];
// A duration of zero means less than one minute
// set it to one minute
if (durationInMinutes == 0)
{
durationInMinutes = 1;
}
else if (durationInMinutes == 1439)
{
// FIXME Add Missing minute if needed
durationInMinutes = 1440;
}
var nbMinutesLeft = durationInMinutes % 60;
var nbHoursAtOneHundred = durationInMinutes / 60;
int index = 0;
for (index = lastIndexOnAveragesOn24HoursByHourNew; index < nbHoursAtOneHundred + lastIndexOnAveragesOn24HoursByHourNew; index++)
{
#if DEBUG
Debug.Assert(index <= 23);
#endif
if (lastMinuteLeftOnLastHour != 0)
{
averagesOn24HoursByHourNew[index].level2 += lastMinuteLeftOnLastHour * 100 / 60;
lastMinuteLeftOnLastHour = 0;
}
else
{
averagesOn24HoursByHourNew[index].level2 += 100;
}
datiCountForOneHour[index] += 1;
}
#if DEBUG
// When th whole day is processed the index will be 24
Debug.Assert(index < 25);
#endif
if (nbMinutesLeft != 0)
{
averagesOn24HoursByHourNew[index].level2 += nbMinutesLeft * 100 / 60;
if (lastMinuteLeftOnLastHour != 0 && lastMinuteLeftOnLastHour > nbMinutesLeft)
{
lastMinuteLeftOnLastHour -= nbMinutesLeft;
}
}
lastIndexOnAveragesOn24HoursByHourNew = index;
}
else if (levels[indexLevel] == 3)
{
int durationInMinutes = (int)minutes[indexLevel];
// A duration of zero means less than one minute
// set it to one minute
if (durationInMinutes == 0)
{
durationInMinutes = 1;
}
else if (durationInMinutes == 1439)
{
// FIXME Add Missing minute if needed
durationInMinutes = 1440;
}
var nbMinutesLeft = durationInMinutes % 60;
var nbHoursAtOneHundred = durationInMinutes / 60;
int index = 0;
for (index = lastIndexOnAveragesOn24HoursByHourNew; index < nbHoursAtOneHundred + lastIndexOnAveragesOn24HoursByHourNew; index++)
{
#if DEBUG
Debug.Assert(index <= 23);
#endif
if (lastMinuteLeftOnLastHour != 0)
{
averagesOn24HoursByHourNew[index].level3 += lastMinuteLeftOnLastHour * 100 / 60;
lastMinuteLeftOnLastHour = 0;
}
else
{
averagesOn24HoursByHourNew[index].level3 += 100;
}
datiCountForOneHour[index] += 1;
}
#if DEBUG
// When th whole day is processed the index will be 24
Debug.Assert(index < 25);
#endif
if (nbMinutesLeft != 0)
{
averagesOn24HoursByHourNew[index].level3 += nbMinutesLeft * 100 / 60;
if (lastMinuteLeftOnLastHour != 0 && lastMinuteLeftOnLastHour > nbMinutesLeft)
{
lastMinuteLeftOnLastHour -= nbMinutesLeft;
}
}
lastIndexOnAveragesOn24HoursByHourNew = index;
}
else if (levels[indexLevel] == 4)
{
int durationInMinutes = (int)minutes[indexLevel];
// A duration of zero means less than one minute
// set it to one minute
if (durationInMinutes == 0)
{
durationInMinutes = 1;
}
else if (durationInMinutes == 1439)
{
// FIXME Add Missing minute if needed
durationInMinutes = 1440;
}
var nbMinutesLeft = durationInMinutes % 60;
var nbHoursAtOneHundred = durationInMinutes / 60;
int index = 0;
for (index = lastIndexOnAveragesOn24HoursByHourNew; index < nbHoursAtOneHundred + lastIndexOnAveragesOn24HoursByHourNew; index++)
{
#if DEBUG
Debug.Assert(index <= 23);
#endif
if (lastMinuteLeftOnLastHour != 0)
{
averagesOn24HoursByHourNew[index].level4 += lastMinuteLeftOnLastHour * 100 / 60;
lastMinuteLeftOnLastHour = 0;
}
else
{
averagesOn24HoursByHourNew[index].level4 += 100;
}
datiCountForOneHour[index] += 1;
}
#if DEBUG
// When th whole day is processed the index will be 24
Debug.Assert(index < 25);
#endif
if (nbMinutesLeft != 0)
{
averagesOn24HoursByHourNew[index].level4 += nbMinutesLeft * 100 / 60;
if (lastMinuteLeftOnLastHour != 0 && lastMinuteLeftOnLastHour > nbMinutesLeft)
{
lastMinuteLeftOnLastHour -= nbMinutesLeft;
}
}
lastIndexOnAveragesOn24HoursByHourNew = index;
}
else if (levels[indexLevel] == 5)
{
int durationInMinutes = (int)minutes[indexLevel];
// A duration of zero means less than one minute
// set it to one minute
if (durationInMinutes == 0)
{
durationInMinutes = 1;
}
else if (durationInMinutes == 1439)
{
// FIXME Add Missing minute if needed
durationInMinutes = 1440;
}
var nbMinutesLeft = durationInMinutes % 60;
var nbHoursAtOneHundred = durationInMinutes / 60;
int index = 0;
for (index = lastIndexOnAveragesOn24HoursByHourNew; index < nbHoursAtOneHundred + lastIndexOnAveragesOn24HoursByHourNew; index++)
{
#if DEBUG
Debug.Assert(index <= 23);
#endif
if (lastMinuteLeftOnLastHour != 0)
{
averagesOn24HoursByHourNew[index].level5 += lastMinuteLeftOnLastHour * 100 / 60;
lastMinuteLeftOnLastHour = 0;
}
else
{
averagesOn24HoursByHourNew[index].level5 += 100;
}
datiCountForOneHour[index] += 1;
}
#if DEBUG
// When th whole day is processed the index will be 24
Debug.Assert(index < 25);
#endif
if (nbMinutesLeft != 0)
{
averagesOn24HoursByHourNew[index].level5 += nbMinutesLeft * 100 / 60;
if (lastMinuteLeftOnLastHour != 0 && lastMinuteLeftOnLastHour > nbMinutesLeft)
{
lastMinuteLeftOnLastHour -= nbMinutesLeft;
}
}
lastIndexOnAveragesOn24HoursByHourNew = index;
}
else
{
throw new InvalidOperationException("Invalid protection level found in stats");
}
}
You can try it this way. Probably not the most elegant solution, but gets the job done and can be a basis for further optimization. For explanation see comments in the code.
using System;
using System.Linq;
public class Program
{
class percentages {
public double l0;
public double l1;
public double l2;
public double l3;
public double l4;
public double l5;
public string ToString() {
return $"{l0:F2} {l1:F2} {l2:F2} {l3:F2} {l4:F2} {l5:F2} ";
}
}
public static void Main()
{
var levels = new int[]{0,5,0};
var minutes = new int[]{658, 1, 781};
var plist = new percentages[24];
//sum up the minutes to total duration on this day
//ie minutes will become [658, 659, 1440]
for (int i = 1; i < minutes.Length; i++)
minutes[i] += minutes[i-1];
//lindex is the current index in the levels/minutes array
var lindex = 0;
//pindex is the current index in the percentages array
var pindex = 0;
var p = new percentages();
//a constant of how much 1 minute contributes in percent of an hour
var m1 = 100.0 / 60;
//check every minute of the day
for (int m = 1; m <= 1440; m++) {
//increment the respective level by 1 minute
switch(levels[lindex]) {
case 0: p.l0 += m1; break;
case 1: p.l1 += m1; break;
case 2: p.l2 += m1; break;
case 3: p.l3 += m1; break;
case 4: p.l4 += m1; break;
case 5: p.l5 += m1; break;
}
//if the minutes reached a level change increment the index in the level/minute array
if (m == minutes[lindex]) lindex++;
//if the minutes reached a full hour, add the current percentages to the list, increment index and reset for the next hour
if (m % 60 == 0){
plist[pindex++] = p;
Console.WriteLine(p.ToString());
p = new percentages();
}
}
}
}
Be aware, there are no sanity checks whatsoever. This will break if levels and minutes don't have the same length or if the sum of minutes is not 1440. For further use, you should add these checks.
I suggest you create another array level_at_min where the index is a minute in the day.
level_at_min will be of size 1440 (I show an algorithm to do it later).
In your example you will have
level_at_min[0] = 0
...
level_at_min[657] = 0
level_at_min[658] = 5
level_at_min[659] = 0
...
level_at_min[1439] = 0
If you have that array, you can create an array of lists (of length 60) levels_at_hour,
that will give for your example
levels_at_hour[0] = [0,0, ..., 0]
levels_at_hour[1] = [0,0, ..., 0]
....
levels_at_hour[11] = [0,..., 5,0]
...
levels_at_hour[23] = [0,0,...,0]
With this you can compute the average protection level at each hour, or the percentage of each protection level at each hour, whatever you want.
Algorithm to create level_at_min: (n the length of array levels and array minutes)
minute_counter = 0
for each block in 0 to n-1
for each minute in minute_counter to (minute_counter+minutes[block])
level_at_min[min] = levels[block]
minute_counter = minute_counter + minutes[block]
Algorithm to create levels_at_hour:
for each hour in 0 to 23:
for each minute in i*60 to (i+1)*60
add level_at_min[minute] to the list levels_at_hour[hour]
This question already has answers here:
Random number generator only generating one random number
(15 answers)
Closed 1 year ago.
I 'm creating a Text Base arena rpg where each day new monsters are add to the list, but only one monster get add to the list repeatly with the same stats which for some reason keeps increasing each day.
What i need are that diferent objects with diferent values are created than add to a list, the second part works well.
This method calls the creator.
public static List<Monster> MonsterOfTheDay()
{
int count = 0;
List<Monster> MonstersListOfTheDay = new List<Monster>();
while(count <= 5)
{
MonstersListOfTheDay.Add(Creator());
count++;
}
return MonstersListOfTheDay;
}
This are the creator
public static Monster Creator()
{
Random random = new Random();
Monster monsterChoosen = monsterListPrefab.Find(m => m.Id == random.Next(0, monsterListPrefab.Count -1));
monsterChoosen.Level = random.Next(monsterChoosen.Level, monsterChoosen.Level + 3);
//1Offensive, 2Defensive, 3Balance
monsterChoosen.Type = (Types)typeList.GetValue(random.Next(1, typeList.Length));
Console.WriteLine("Estou Aqui");
int atributes = monsterChoosen.Level * 3;
int spend = 0;
Console.WriteLine("Estou Aqui");
while(spend != atributes)
{
int chance = random.Next(0, 100);
if(monsterChoosen.Type == Types.Offensive)
{
if(chance >= 0 && chance <= 60)
{
monsterChoosen.Str++;
spend++;
}
if(chance >= 61 && chance <= 70)
{
monsterChoosen.Int++;
spend++;
}
if(chance >= 71 && chance <= 85)
{
monsterChoosen.Agi++;
spend++;
}
if(chance >= 86 && chance <= 100)
{
monsterChoosen.Vig++;
spend++;
}
}
else if(monsterChoosen.Type == Types.Defensive)
{
if(chance >= 0 && chance <= 60)
{
monsterChoosen.Vig++;
spend++;
}
if(chance >= 61 && chance <= 70)
{
monsterChoosen.Str++;
spend++;
}
if(chance >= 71 && chance <= 85)
{
monsterChoosen.Int++;
spend++;
}
if(chance >= 86 && chance <= 100)
{
monsterChoosen.Agi++;
spend++;
}
}
else if(monsterChoosen.Type == Types.Balance)
{
if(chance >= 0 && chance <= 25)
{
monsterChoosen.Str++;
spend++;
}
if(chance >= 26 && chance <= 50)
{
monsterChoosen.Int++;
spend++;
}
if(chance >= 51 && chance <= 75)
{
monsterChoosen.Agi++;
spend++;
}
if(chance >= 76 && chance <= 100)
{
monsterChoosen.Vig++;
spend++;
}
}
else if(monsterChoosen.Type == Types.Prefab)
{
spend++;
}
else
{
Console.WriteLine("Error");
}
}
return monsterChoosen;
}
I chance the initial 3 lines of the Creator method, now its working properly, the reason is, as Phillipp said in the game developer stack, the old code keep the information of the monsterChoosen variable and won't generate a new one when called again, keeping the same result and only increasing its stats and level, now with the new line of the variable, monsterChoosen can update every time its called.
Random random = new Random();
int randId = random.Next(2);
Monster monsterChoosen = new Monster(monsterListPrefab.Find(m => m.Id == randId));
I have a method that calculates the waiting time in a queue. It works fine for a small range. However, you can quickly see that this would become very tedious to do with a large range. In this example, if you are #1 in the queue, your wait time is 'very soon'. If it's greater than 1 and less than 5: 0 to 1 weeks, and so on... How can I loop through this list to dynamically find the place in the queue?
if ((PlaceInQueue) <= 1)
{
result = "Very soon!";
}
if ((PlaceInQueue) > 1 & (PlaceInQueue) < 5)
{
result = "From 0 to 1 weeks.";
}
if ((PlaceInQueue) >= 5 & (PlaceInQueue) < 11)
{
result = "From 1 to 2 weeks.";
}
if ((PlaceInQueue) >= 11 & (PlaceInQueue) < 17)
{
result = "From 2 to 3 weeks.";
}
if ((PlaceInQueue) >= 17 & (PlaceInQueue) < 23)
{
result = "From 3 to 4 weeks.";
}
Here's what I've started and what I'm trying to accomplish. The first few if statements before the while loop may need to be hard coded as the math isn't exact and the rest would be dynamic. So, in this example, the results are correct up until the place in the queue is 11 or greater (inside the while loop).
int n = 1;
int max = 300; // Stop calculating when the max is reached
var PlaceInQue = (Convert.ToInt32(placeInQueue)); // This is the position in the Que
foreach (var item in PlaceInQue)
{
if (PlaceInQue <= 1)
{
result = "Very soon!";
}
if (PlaceInQue > 1 & PlaceInQue < 5)
{
result = "From 0 to 1 weeks.";
}
if (PlaceInQue >= 5 & PlaceInQue < 11)
{
result = "From 1 to 2 weeks.";
}
while (n < max)
{
if (PlaceInQue >= (should increment from 11 and then 17 then 23 then 29 and so on...) & PlaceInQue < (increment from 17 then 23 then 29 then 35 and so on...)
{
result = (should increment from "2 to 3 weeks" and then "3 to 4 weeks" and so on until max is reached...)
}
n++;
}
}
I think you need something like this:
if (PlaceInQue <= 1)
{
result = "Very soon!";
}
else if (PlaceInQue < 5)
{
result = "From 0 to 1 weeks.";
}
else if (PlaceInQue < 11)
{
result = "From 1 to 2 weeks.";
}
else if
{
for (int n = 11; n <= max; n += 5)
{
if (PlaceInQue >= n && PlaceInQue < n + 5)
{
int weeks = n / 5;
result = $"From {weeks} to {(weeks + 1)} weeks.";
break;
}
}
}
Below code works for me for which I have checked the probable edge cases. Let me know if it doesn't work for you.
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
Queue<int> queue = new Queue<int>(Enumerable.Range(1, 300));
foreach (var placeInQueue in queue)
{
if(placeInQueue <= 1)
Console.WriteLine($"Place: {placeInQueue}. Very soon!");
else if(placeInQueue < 300)
{
var fromTo = GetFromTo(placeInQueue);
Console.WriteLine($"Place: {placeInQueue}. From {fromTo.Item1} to {fromTo.Item2} weeks.");
}
}
}
private static Tuple<int,int> GetFromTo(int place)
{
if (place < 5)
return new Tuple<int, int>(0, 1);
var q1 = place / 5;
var q2 = 0;
if((place + 1) % 6 == 0)
{
q2 = (place + 1) / 6;
q1 = int.MaxValue;
}
else
q2 = (place/6) == 0 ? q1 : (place/6);
var from = Math.Min(q1, q2);
var to = from + 1;
return new Tuple<int, int>(from, to);
}
}
private void timer_click1(object sender, RoutedEventArgs e)
{
seconds = seconds - 1;
if (seconds == -1)
{
minutes = minutes - 1;
seconds = 59;
}
if (minutes == -1)
{
hours = hours - 1;
minutes = 59;
}
if (hours == 0 && minutes == 0 && seconds == 0)
{
timer.Stop();
}
string hhr = Convert.ToString(hours);
string minns = Convert.ToString(minutes);
string seccs = Convert.ToString(seconds);
}
I'm trying to create a countdown timer. I am stuck with hhr, minns and seccs because I have to display the countdown in one label not more. How can I pass these three text as hrr:minns:seccs?
There are probably better ways to get the remaining time but here is how you could use the string.Format method to display all three components in a single string:
private void timer_click1(object sender, RoutedEventArgs e)
{
seconds = seconds - 1;
if (seconds == -1)
{
minutes = minutes - 1;
seconds = 59;
}
if (minutes == -1)
{
hours = hours - 1;
minutes = 59;
}
if (hours == 0 && minutes == 0 && seconds == 0)
{
timer.Stop();
}
string hhr = Convert.ToString(hours);
string minns = Convert.ToString(minutes);
string seccs = Convert.ToString(seconds);
string s = string.Format("{0}:{1}:{2}", hhr, minns, seccs);
lbl.Text = s;
}
In C#6+ it's even eaiser:
string s = $"{hhr}:{minns}:{seccs}";
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
So I'm doing the 7th Project Euler problem, and I'm not sure why this code isn't working, it seems to be okay so small numbers, I've tested 1-10 and it's fine, but doesn't return the correct answer at 10001 - returns 104745.
And yes, I know it's inefficient.
private void eulerSeven(int num)
{
// Start the Prime count at 3, with 2 already counted.
int primecount = 1, counter = 3;
//While num of primes counted < the nth prime
while (primecount < num)
{
bool isPrime = true;
//check every number from 2 -> the current number we're checking
for (int i = 2; i < counter; i++)
{
if (counter%i == 0)
{
//if divisible, not a prime
isPrime = false;
break;
}
}
if (isPrime) //If is a prime, increment counter
{ primecount++; }
// Go to next number (only checking odds)
counter += 2;
}
//output nth prime
Console.WriteLine(counter);
}
As stated by #lanorkin, the problem was:
should be counter - 2
but also, I would like to suggest a look at https://codereview.stackexchange.com/questions/124644/project-euler-7-10001st-prime, so this code should do the same, but very very fast (5ms on my machine):
static void Main(string[] args)
{
var stopwatch = Stopwatch.StartNew();
Console.WriteLine(CalculateEulerSeven(10001)); // should be 104745
stopwatch.Stop();
Console.WriteLine("Time to calculate in milliseconds : {0}", stopwatch.ElapsedMilliseconds);
Console.ReadKey();
}
private static int CalculateEulerSeven(int num)
{
int primecount = 1, counter = 3;
while (primecount < num)
{
bool isPrime = IsPrime(counter);
if (isPrime) primecount++;
counter += 2;
}
return counter;
}
static bool IsPrime(int value)
{
if (value < 2) { return false; }
if (value % 2 == 0) { return value == 2; }
if (value % 3 == 0) { return value == 3; }
if (value % 5 == 0) { return value == 5; }
if (value == 7) { return true; }
for (int divisor = 7; divisor * divisor <= value; divisor += 30)
{
if (value % divisor == 0) { return false; }
if (value % (divisor + 4) == 0) { return false; }
if (value % (divisor + 6) == 0) { return false; }
if (value % (divisor + 10) == 0) { return false; }
if (value % (divisor + 12) == 0) { return false; }
if (value % (divisor + 16) == 0) { return false; }
if (value % (divisor + 22) == 0) { return false; }
if (value % (divisor + 24) == 0) { return false; }
}
return true;
}