DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

A Solution For The "Primary Arithmetic" Problem

04.13.2008
| 5448 views |
  • submit to reddit
        A solution for the "Primary Arithmetic" problem.

Problem description:
<a href="http://icpcres.ecs.baylor.edu/onlinejudge/external/100/10035.html">http://icpcres.ecs.baylor.edu/onlinejudge/external/100/10035.html</a>

Author: <a href="http://joanatrindade.wikidot.com">Joana Matos Fonseca da Trindade</a>
Date: 2008.04.04

/**
 * Solution for the "Primary Arithmetic" problem.
 * UVa ID: 10035
 */ 
#include <iostream.h> 
#include <stdlib.h> 

using namespace std; 

int main() {
    unsigned long long n1; /* 1st number */ 
    unsigned long long n2; /* 2nd number */ 
    int carry = 0; /* carry */ 
    int sum = 0; /* temporary sum */ 
    int count = 0; /* carry counter */ 

    while(cin >> n1 >> n2 && ((n1 > 0) || (n2 > 0))) { 
        carry = 0; 
	count = 0; 
	sum = 0; 

	/* while there's still something.. */ 
	while ((n1 > 0) || (n2 > 0)) { 
	    /* sum the two right-most digits */ 
	    sum = carry + (n1 % 10) + (n2 % 10); 

	    if (sum >= 10) { 
		count++; 
	    } 
			
	    /* get the carry by dividing the sum of the two digits */ 
	    carry = sum / 10; 

	    /* 'reduce' the numbers by ten, to update the right-most digits */ 
	    n1 /= 10; 
            n2 /= 10; 
	} 
		
	if (count == 0) { 
            cout << "No carry operation." << endl; 
	} else if (count == 1) { 
	    cout << "1 carry operation." << endl; 
	} else { 
            cout << count << " carry operations." << endl; 
        } 
    } 

    return 0;
} 
    

Comments

Snippets Manager replied on Thu, 2010/07/29 - 2:09am

Here is another solution: #include int carrycount(int n1, int n2) { static int carry = 0; int result = 0; if (n1 == 0 && n2 == 0) { return 0; } int x = n1/10; int y = n2/10; int x1 = n1 - x*10; int y1 = n2 - y*10; carry = ((carry + x1 + y1) > 9 ? 1: 0); result = carry; result += carrycount(x, y); return result; } int main() { int n1, n2; printf("Enter 2 numbers for computing carry\n"); scanf("%d %d", &n1, &n2); printf("Carry count: %d\n", carrycount(n1, n2)); return 0; }