# Thread: Design fastest algorithm to specify nearest Friday 13th

1. ## Design fastest algorithm to specify nearest Friday 13th

Hi all,
Friday 13th is a bad day to do somethings and I think that specify nearest Friday 13h is a funny exercise.
Exercise:
Design fastest algorithm to specify nearest Friday 13th with two directions - and +

example: current friday 13 is 13th October 2006.

nearest Friday 13th is 13th Junuary 2006 with direction -
rearest Friday 13h is 13th April 2007 with direction +

2. Are funny excercises not dignified enough for you to put your brain to doing? Show effort.

3. might be your best friend

Code:
#include <time.h>

4. If that's an interesting attempt at getting someone to do your homework, perhaps I bit. It made for an interesting diversion for me.

But since such things are frowned upon, I did make it something that it would be difficult to explain to an instructor if grades might be involved.
Code:
/**
* Find the next or previous Friday the 13th.
* @param  target     pointer to tm structure containing result
* @param  start      pointer to tm structure containing beginning date
* @param  direction  nonnegative indicates forward, negative indicates backward
* @return nonzero if the date was found and the target successfully filled
*/
int FridayThe13th(struct tm *target, const struct tm *start, int direction)
{
time_t guess;
const int move = direction < 0 ? -1 : 1;
while ( *target = *start, target->tm_mon += move,
(guess = mktime(target)) != (time_t)-1 &&
(start = localtime(&guess)) != NULL &&
target->tm_wday != 5 );
return 1;
}
And this doesn't shoot for speed.

And in fact, this doesn't handle some UB very well; that went out with the "compacting".

5. use the congruence

Code:
w=floor(k+floor(2.6m-0.2)-2C+y+floor(y/2)+floor(c/4))mod7
and iterate over each month.

Popular pages Recent additions