For UVa problem 10783 (Odd Sum), one just has to sum up all the odd numbers between two numbers, a and b. Things can get slow if for each number between a and b, one checked if that number were odd or even, like in the following code:
for (i = a, sum = 0; i <= b; i += 1) {
__j = i mod 2;
__if (j == 1) {
____sum += i;
__}
}
To hasten the computation, we can start at an odd number in the for-loop and add 2 to the iterator index for each iteration.
First we check if a is odd or even. If it is even, we increment it to make it odd. Then we go to the for-loop:
for (j = a, sum = 0; j <= b; j += 2) {
__sum += j;
}
Showing posts with label odd numbers. Show all posts
Showing posts with label odd numbers. Show all posts
Saturday, January 17, 2009
UVa problem 10783: sample code
001 #include "stdio.h"
002
003 int main() {
004 char line[100];
005
006 int num_cases
007 , i
008 , j
009 , k
010 , a
011 , b
012 , sum
013 ;
014
015 fgets(line, 100, stdin);
016 sscanf(line, "%d", &num_cases);
017
018 for (i = 1; i <= num_cases; i += 1) {
019 fgets(line, 100, stdin);
020 sscanf(line, "%d", &a);
021
022 fgets(line, 100, stdin);
023 sscanf(line, "%d", &b);
024
025 k = a & 1;
026 if (k == 0) {
027 a += 1;
028 }
029
030 for (j = a, sum = 0; j <= b; j += 2) {
031 sum += j;
032 }
033
034 printf("Case %d: %d\n", i, sum);
035 }
036
037 return 0;
038 }
Labels:
10783,
answer,
clue,
hint,
odd numbers,
Odd Sum,
problem,
sample algorithm,
sample code,
sample solution,
sum,
tip,
UVA Online Judge
Subscribe to:
Posts (Atom)