Canola  0.8.D001
lib/number/z/multiplication.cc
Go to the documentation of this file.
00001 //
00002 // canola - canon canola 1614p emulator
00003 // Copyright (C) 2012 Peter Miller
00004 //
00005 // This program is free software; you can redistribute it and/or modify
00006 // it under the terms of the GNU General Public License, version 3, as
00007 // published by the Free Software Foundation.
00008 //
00009 // This program is distributed in the hope that it will be useful,
00010 // but WITHOUT ANY WARRANTY; without even the implied warranty of
00011 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00012 // General Public License for more details.
00013 //
00014 // You should have received a copy of the GNU General Public License along
00015 // with this program. If not, see <http://www.gnu.org/licenses/>.
00016 //
00017 
00018 #include <lib/ac/assert.h>
00019 
00020 #include <lib/number/z.h>
00021 
00022 
00023 number_z &
00024 number_z::operator*=(const number_z &rhs)
00025 {
00026     *this = *this * rhs;
00027     return *this;
00028 }
00029 
00030 
00031 number_z
00032 number_z::operator*(const number_z &rhs)
00033     const
00034 {
00035     assert(is_valid());
00036     assert(rhs.is_valid());
00037 
00038     // short circuit the easy cases
00039     if (is_zero() || rhs.is_zero())
00040         return number_z();
00041     if (is_one())
00042         return rhs;
00043     if (rhs.is_one())
00044         return *this;
00045 
00046     number_z result;
00047     for (size_t j = 0; j < digits_used; ++j)
00048     {
00049         unsigned carry = 0;
00050         for (size_t k = 0; k < rhs.digits_used || carry; ++k)
00051         {
00052             unsigned dsum =
00053                 result.get(j + k) + digits[j] * rhs.get(k) + carry;
00054             carry = dsum / 10;
00055             result.set(j + k, dsum % 10);
00056         }
00057     }
00058     return result;
00059 }
00060 
00061 
00062 // vim: set ts=8 sw=4 et :