Busan IT/Algorithm2016. 1. 1. 13:01

Calculating a sum of serial number is a simple math with loop and 'if' state.

 

However, without them, it needs some brain work.

 

This is an expression, the sum of arithmetic progression.

 



** n: a number of series, a1: first number, an: last number

 

Problem is we cannot know which number is greater. Without if state, there is no way to get a right answer.

 

So what I've done is to print out the both cases, first number is greater and second number is greater.



 

Code goes...


// Algorithm for finding sum of serial number
// without using 'if' state

#include <stdio.h>
#include <math.h>

int main(void)
{
  int iNum1, iNum2;
  int iCnt1, iCnt2;
  int iSum1, iSum2;

  puts("Input two numbers");
  scanf("%d %d"&iNum1, &iNum2);

  iCnt1 = iNum2 - iNum1 +1;
  iCnt2 = iNum1 - iNum2 +1;

  iSum1 = (iCnt1 * (iNum1 + iNum2))/2;
  iSum2 = (iCnt2 * (iNum1 + iNum2))/2;

  puts("If a second number is bigger than first one, the answer is [iSum1] or else");
  printf("Sum1 is [%d] and Sum2 is [%d]\n", iSum1, iSum2);
  
  return


 

 

 

 

 

 

반응형

'Busan IT > Algorithm' 카테고리의 다른 글

GCD(Greatest Common Divisor)  (0) 2015.12.29
Posted by newind2000