Hacker Timesnew | past | comments | ask | show | jobs | submitlogin

Weird example, but fine, we can reduce the number of modulo operations if that is the one with the 'cost', but that's not very realistic given that we're printing stuff to stdout, but if we take your premise as true and we optimize for the cost of the modulo operator you would get silly solutions like this:

  main()

  {
	int i;
	int ncounters = 2;
	int counters[2] ;
	int presets[2] = { 5, 3};
	int n; // number of counters that tripped
	int j; 
	char * strings[2] = { "fizz", "buzz" };

        // first time, copy presets to counters

	for (j=0;j<ncounters;j++) {
		counters[j] = presets[j];
	}

	for (i=1;i<=100;i++) {
		n = 0;	// reset number of counters that have zeroed

		for (j=0;j<ncounters;j++) {
			counters[j] = counters[j] - 1;

                        // output relevant string when counter trips

			if (counters[j] == 0) {
                                // separate strings by dashes if more than one counter trips
				if (n != 0) {
					printf("-");
				}
				n++;
				counters[j] = presets[j];
				printf("%s",strings[j]);
			}
		}
                // no counter tripped, just output the number
		if (n == 0) {
			printf("%d",i);
		}
		printf("\n");
	}
  }
Forgive the lack of comments and the hardcoded number of strings.

No modulo operations.

By asking the question that way you'd get solutions that you're not really looking for.



The short version

  int c3 = 1;
  int c5 = 1;
  for ( int i = 1; i <= 100; i++, c3++, c5++ ){

	if ( c3 == 3 ){ printf( "FIZZ" ); c3 = 0; }

	if ( c5 == 5 ){ printf( "BUZZ" ); c5 = 0; }

	if ( c3 && c5 ){ printf( "%d", i ); }
  }


You're missing the needed printf("\n"); at the end of the loop.

Elegant solution, but fails to meet the problem specification.


Hehe, compact.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: