_id
stringlengths
2
5
text
stringlengths
7
10.9k
title
stringclasses
1 value
c756
#include <iostream> using namespace std; int main() { int a, b; cin >> a >> b; cout << a + b << endl; }
c757
#include <iostream> #include "math.h" #include "boost/rational.hpp" typedef boost::rational<int> frac; bool is_perfect(int c) { frac sum(1, c); for (int f = 2;f < sqrt(static_cast<float>(c)); ++f){ if (c % f == 0) sum += frac(1,f) + frac(1, c/f); } if (sum.denominator() == 1){ return (sum == 1); } return false; } int main() { for (int candidate = 2; candidate < 0x80000; ++candidate){ if (is_perfect(candidate)) std::cout << candidate << " is perfect" << std::endl; } return 0; }
c758
#include <cmath> #include <iostream> #include <numbers> static const double DegreesPerHour = 15.0; static const double DegreesPerRadian = 180.0 * std::numbers::inv_pi; struct SundialCalculation { double HourAngle; double HourLineAngle; }; class Sundial { double m_sinLatitude; double m_timeZoneCorrection; public: Sundial(double latitude, double longitude, double legalMeridian) noexcept : m_sinLatitude(sin(latitude / DegreesPerRadian)) , m_timeZoneCorrection(legalMeridian - longitude) {} SundialCalculation CalculateShadow(double hoursSinceNoon) const noexcept { double hourAngle = hoursSinceNoon * DegreesPerHour + m_timeZoneCorrection; double hourAngleRad = hourAngle / DegreesPerRadian; double hlaRad = atan2(m_sinLatitude * sin(hourAngleRad), cos(hourAngleRad)); double hourLineAngle = hlaRad * DegreesPerRadian; return SundialCalculation {hourAngle, hourLineAngle}; } }; int main() { double latitude, longitude, legalMeridian; std::cout << "Enter latitude:"; std::cin >> latitude; std::cout << "Enter longitude:"; std::cin >> longitude; std::cout << "Enter legal meridian:"; std::cin >> legalMeridian; const Sundial sundial(latitude, longitude, legalMeridian); for(int hour = -6; hour < 7; ++hour) { auto result = sundial.CalculateShadow(hour); auto amOrPm = hour < 0 ? "am" : "pm"; auto hourString = std::to_string(hour < 1 ? 12 + hour : hour); std::cout << hourString << amOrPm << " - sun hour angle:" << result.HourAngle << ", dial hour line angle:" << result.HourLineAngle << "\n"; } }
c759
#include <iostream> #include <iterator> #include <vector> using namespace std; typedef vector<double> Poly; void Print(char name, const Poly &A) { cout << name << "(" << A.size()-1 << ") = [ "; copy(A.begin(), A.end(), ostream_iterator<decltype(A[0])>(cout, " ")); cout << "]\n"; } int main() { Poly N, D, d, q, r; size_t dN, dD, dd, dq, dr; size_t i; cout << "Enter the degree of N: "; cin >> dN; cout << "Enter the degree of D: "; cin >> dD; dq = dN-dD; dr = dN-dD; if( dD < 1 || dN < 1 ) { cerr << "Error: degree of D and N must be positive.\n"; return 1; } N.resize(dN+1); cout << "Enter the coefficients of N:"<<endl; for ( i = 0; i <= dN; i++ ) { cout << "N[" << i << "]= "; cin >> N[i]; } D.resize(dN+1); cout << "Enter the coefficients of D:"<<endl; for ( i = 0; i <= dD; i++ ) { cout << "D[" << i << "]= "; cin >> D[i]; } d.resize(dN+1); q.resize(dq+1); r.resize(dr+1); cout << "-- Procedure --" << endl << endl; if( dN >= dD ) { while(dN >= dD) { d.assign(d.size(), 0); for( i = 0 ; i <= dD ; i++ ) d[i+dN-dD] = D[i]; dd = dN; Print( 'd', d ); q[dN-dD] = N[dN]/d[dd]; Print( 'q', q ); for( i = 0 ; i < dq + 1 ; i++ ) d[i] = d[i] * q[dN-dD]; Print( 'd', d ); for( i = 0 ; i < dN + 1 ; i++ ) N[i] = N[i] - d[i]; dN--; Print( 'N', N ); cout << "-----------------------" << endl << endl; } } for( i = 0 ; i <= dN ; i++ ) r[i] = N[i]; cout << "=========================" << endl << endl; cout << "-- Result --" << endl << endl; Print( 'q', q ); Print( 'r', r ); }
c760
#include <iostream> #include <numeric> #include <functional> #include <vector> int main() { std::vector<int> nums = { 1, 2, 3, 4, 5 }; auto nums_added = std::accumulate(std::begin(nums), std::end(nums), 0, std::plus<int>()); auto nums_other = std::accumulate(std::begin(nums), std::end(nums), 0, [](const int& a, const int& b) { return a + 2 * b; }); std::cout << "nums_added: " << nums_added << std::endl; std::cout << "nums_other: " << nums_other << std::endl; }
c761
#include <string> #include "Poco/URI.h" #include <iostream> int main( ) { std::string encoded( "http%3A%2F%2Ffoo%20bar%2F" ) ; std::string decoded ; Poco::URI::decode ( encoded , decoded ) ; std::cout << encoded << " is decoded: " << decoded << " !" << std::endl ; return 0 ; }
c762
#include <chrono> #include <csignal> #include <ctime> #include <iostream> #include <thread> volatile sig_atomic_t gotint = 0; void handler(int signum) { gotint = 1; } int main() { using namespace std; signal(SIGINT, handler); int i = 0; clock_t startTime = clock(); while (true) { if (gotint) break; std::this_thread::sleep_for(std::chrono::milliseconds(500)); if (gotint) break; cout << ++i << endl; } clock_t endTime = clock(); double dt = (endTime - startTime) / (double)CLOCKS_PER_SEC; cout << "Program has run for " << dt << " seconds" << endl; return 0; }
c763
#include <iostream> int main() { unsigned int a = 1, b = 1; unsigned int target = 48; for(unsigned int n = 3; n <= target; ++n) { unsigned int fib = a + b; std::cout << "F("<< n << ") = " << fib << std::endl; a = b; b = fib; } return 0; }
c764
int i = 1024; while(i > 0){ std::cout << i << std::endl; i /= 2; }
c765
#include <iostream> double f(double x); int main() { unsigned int start = 1; unsigned int end = 1000; double sum = 0; for( unsigned int x = start; x <= end; ++x ) { sum += f(x); } std::cout << "Sum of f(x) from " << start << " to " << end << " is " << sum << std::endl; return 0; } double f(double x) { return ( 1.0 / ( x * x ) ); }
c766
#include <cassert> #include <iostream> typedef unsigned long ulong; ulong egyptian_division(ulong dividend, ulong divisor, ulong* remainder) { constexpr int SIZE = 64; ulong powers[SIZE]; ulong doublings[SIZE]; int i = 0; for (; i < SIZE; ++i) { powers[i] = 1 << i; doublings[i] = divisor << i; if (doublings[i] > dividend) { break; } } ulong answer = 0; ulong accumulator = 0; for (i = i - 1; i >= 0; --i) { if (accumulator + doublings[i] <= dividend) { accumulator += doublings[i]; answer += powers[i]; } } if (remainder) { *remainder = dividend - accumulator; } return answer; } void print(ulong a, ulong b) { using namespace std; ulong x, y; x = egyptian_division(a, b, &y); cout << a << " / " << b << " = " << x << " remainder " << y << endl; assert(a == b * x + y); } int main() { print(580, 34); return 0; }
c767
template<class ForwardIterator> void combsort ( ForwardIterator first, ForwardIterator last ) { static const double shrink_factor = 1.247330950103979; typedef typename std::iterator_traits<ForwardIterator>::difference_type difference_type; difference_type gap = std::distance(first, last); bool swaps = true; while ( (gap > 1) || (swaps == true) ){ if (gap > 1) gap = static_cast<difference_type>(gap/shrink_factor); swaps = false; ForwardIterator itLeft(first); ForwardIterator itRight(first); std::advance(itRight, gap); for ( ; itRight!=last; ++itLeft, ++itRight ){ if ( (*itRight) < (*itLeft) ){ std::iter_swap(itLeft, itRight); swaps = true; } } } }
c768
#include <iostream> #include <algorithm> #include <vector> #include <numeric> void partitions(std::vector<size_t> args) { size_t sum = std::accumulate(std::begin(args), std::end(args), 0); std::vector<size_t> nums(sum); std::iota(std::begin(nums), std::end(nums), 1); do { size_t total_index = 0; std::vector<std::vector<size_t>> parts; for (const auto& a : args) { std::vector<size_t> part; bool cont = true; for (size_t j = 0; j < a; ++j) { for (const auto& p : part) { if (nums[total_index] < p) { cont = false; break; } } if (cont) { part.push_back(nums[total_index]); ++total_index; } } if (part.size() != a) { break; } parts.push_back(part); } if (parts.size() == args.size()) { std::cout << "("; for (const auto& p : parts) { std::cout << "{ "; for (const auto& e : p) { std::cout << e << " "; } std::cout << "},"; } std::cout << ")," << std::endl; } } while (std::next_permutation(std::begin(nums), std::end(nums))); } int main() { std::vector<size_t> args = { 2, 0, 2 }; partitions(args); std::cin.ignore(); std::cin.get(); return 0; }
c769
#include <iostream> #include <string> #include <vector> struct last_letter_first_letter { size_t max_path_length = 0; size_t max_path_length_count = 0; std::vector<std::string> max_path_example; void search(std::vector<std::string>& names, size_t offset) { if (offset > max_path_length) { max_path_length = offset; max_path_length_count = 1; max_path_example.assign(names.begin(), names.begin() + offset); } else if (offset == max_path_length) { ++max_path_length_count; } char last_letter = names[offset - 1].back(); for (size_t i = offset, n = names.size(); i < n; ++i) { if (names[i][0] == last_letter) { names[i].swap(names[offset]); search(names, offset + 1); names[i].swap(names[offset]); } } } void find_longest_chain(std::vector<std::string>& names) { max_path_length = 0; max_path_length_count = 0; max_path_example.clear(); for (size_t i = 0, n = names.size(); i < n; ++i) { names[i].swap(names[0]); search(names, 1); names[i].swap(names[0]); } } }; int main() { std::vector<std::string> names{"audino", "bagon", "baltoy", "banette", "bidoof", "braviary", "bronzor", "carracosta", "charmeleon", "cresselia", "croagunk", "darmanitan", "deino", "emboar", "emolga", "exeggcute", "gabite", "girafarig", "gulpin", "haxorus", "heatmor", "heatran", "ivysaur", "jellicent", "jumpluff", "kangaskhan", "kricketune", "landorus", "ledyba", "loudred", "lumineon", "lunatone", "machamp", "magnezone", "mamoswine", "nosepass", "petilil", "pidgeotto", "pikachu", "pinsir", "poliwrath", "poochyena", "porygon2", "porygonz", "registeel", "relicanth", "remoraid", "rufflet", "sableye", "scolipede", "scrafty", "seaking", "sealeo", "silcoon", "simisear", "snivy", "snorlax", "spoink", "starly", "tirtouga", "trapinch", "treecko", "tyrogue", "vigoroth", "vulpix", "wailord", "wartortle", "whismur", "wingull", "yamask"}; last_letter_first_letter solver; solver.find_longest_chain(names); std::cout << "Maximum path length: " << solver.max_path_length << '\n'; std::cout << "Paths of that length: " << solver.max_path_length_count << '\n'; std::cout << "Example path of that length:\n "; for (size_t i = 0, n = solver.max_path_example.size(); i < n; ++i) { if (i > 0 && i % 7 == 0) std::cout << "\n "; else if (i > 0) std::cout << ' '; std::cout << solver.max_path_example[i]; } std::cout << '\n'; }
c770
#include <windows.h> #include <string> using namespace std; const int BMP_SIZE = 600, CELL_SIZE = 4, GRID_SIZE = BMP_SIZE / CELL_SIZE; const bool INFINIT_RUN = false; enum cellState { WHITE, BLACK, ANT }; enum facing { NOR, EAS, SOU, WES }; enum state { RUNNING, RESTING }; class myBitmap { public: myBitmap() : pen( NULL ) {} ~myBitmap() { DeleteObject( pen ); DeleteDC( hdc ); DeleteObject( bmp ); } bool create( int w, int h ) { BITMAPINFO bi; ZeroMemory( &bi, sizeof( bi ) ); bi.bmiHeader.biSize = sizeof( bi.bmiHeader ); bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8; bi.bmiHeader.biCompression = BI_RGB; bi.bmiHeader.biPlanes = 1; bi.bmiHeader.biWidth = w; bi.bmiHeader.biHeight = -h; HDC dc = GetDC( GetConsoleWindow() ); bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 ); if( !bmp ) return false; hdc = CreateCompatibleDC( dc ); SelectObject( hdc, bmp ); ReleaseDC( GetConsoleWindow(), dc ); width = w; height = h; return true; } void clear() { ZeroMemory( pBits, width * height * sizeof( DWORD ) ); } void setPenColor( DWORD clr ) { if( pen ) DeleteObject( pen ); pen = CreatePen( PS_SOLID, 1, clr ); SelectObject( hdc, pen ); } void saveBitmap( string path ) { BITMAPFILEHEADER fileheader; BITMAPINFO infoheader; BITMAP bitmap; DWORD wb; GetObject( bmp, sizeof( bitmap ), &bitmap ); DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight]; ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) ); ZeroMemory( &infoheader, sizeof( BITMAPINFO ) ); ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) ); infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8; infoheader.bmiHeader.biCompression = BI_RGB; infoheader.bmiHeader.biPlanes = 1; infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader ); infoheader.bmiHeader.biHeight = bitmap.bmHeight; infoheader.bmiHeader.biWidth = bitmap.bmWidth; infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ); fileheader.bfType = 0x4D42; fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER ); fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage; GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS ); HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL ); WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL ); WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL ); WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL ); CloseHandle( file ); delete [] dwpBits; } HDC getDC() const { return hdc; } int getWidth() const { return width; } int getHeight() const { return height; } private: HBITMAP bmp; HDC hdc; HPEN pen; void *pBits; int width, height; }; class Ant { public: Ant() { _bmp.create( BMP_SIZE, BMP_SIZE ); ZeroMemory( _grid, sizeof( _grid ) ); RED_BRUSH = CreateSolidBrush( 255 ); _antState = RUNNING; } ~Ant() { DeleteObject( RED_BRUSH ); } void setPosition( int x, int y ) { _sx = x; _sy = y; _facing = WES; } void mainLoop() { switch( _antState ) { case RUNNING: simulate(); case RESTING: display(); } } void setHWND( HWND hwnd ) { _hwnd = hwnd; } private: void simulate() { switch( _grid[_sx][_sy] ) { case BLACK: _grid[_sx][_sy] = WHITE; if( --_facing < NOR ) _facing = WES; break; case WHITE: _grid[_sx][_sy] = BLACK; if( ++_facing > WES ) _facing = NOR; } switch( _facing ) { case NOR: if( --_sy < 0 ) { if( INFINIT_RUN ) _sy = GRID_SIZE - 1; else _antState = RESTING; } break; case EAS: if( ++_sx >= GRID_SIZE ) { if( INFINIT_RUN ) _sx = 0; else _antState = RESTING; } break; case SOU: if( ++_sy >= GRID_SIZE ) { if( INFINIT_RUN ) _sy = 0; else _antState = RESTING; } break; case WES: if( --_sx < 0 ) { if( INFINIT_RUN ) _sx = GRID_SIZE - 1; else _antState = RESTING; } } } void display() { _bmp.clear(); HBRUSH br; RECT rc; int xx, yy; HDC dc = _bmp.getDC(); for( int y = 0; y < GRID_SIZE; y++ ) for( int x = 0; x < GRID_SIZE; x++ ) { switch( _grid[x][y] ) { case BLACK: br = static_cast<HBRUSH>( GetStockObject( BLACK_BRUSH ) ); break; case WHITE: br = static_cast<HBRUSH>( GetStockObject( WHITE_BRUSH ) ); } if( x == _sx && y == _sy ) br = RED_BRUSH; xx = x * CELL_SIZE; yy = y * CELL_SIZE; SetRect( &rc, xx, yy, xx + CELL_SIZE, yy + CELL_SIZE ); FillRect( dc, &rc, br ); } HDC wdc = GetDC( _hwnd ); BitBlt( wdc, 0, 0, BMP_SIZE, BMP_SIZE, dc, 0, 0, SRCCOPY ); ReleaseDC( _hwnd, wdc ); } myBitmap _bmp; HWND _hwnd; HBRUSH RED_BRUSH; BYTE _grid[GRID_SIZE][GRID_SIZE]; int _sx, _sy, _facing; state _antState; }; class wnd { public: int wnd::Run( HINSTANCE hInst ) { _hInst = hInst; _hwnd = InitAll(); _ant.setHWND( _hwnd ); _ant.setPosition( GRID_SIZE / 2, GRID_SIZE / 2 ); ShowWindow( _hwnd, SW_SHOW ); UpdateWindow( _hwnd ); MSG msg; ZeroMemory( &msg, sizeof( msg ) ); while( msg.message != WM_QUIT ) { if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 ) { TranslateMessage( &msg ); DispatchMessage( &msg ); } else { _ant.mainLoop(); } } return UnregisterClass( "_LANGTONS_ANT_", _hInst ); } private: static int WINAPI wnd::WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) { switch( msg ) { case WM_DESTROY: PostQuitMessage( 0 ); break; default: return DefWindowProc( hWnd, msg, wParam, lParam ); } return 0; } HWND InitAll() { WNDCLASSEX wcex; ZeroMemory( &wcex, sizeof( wcex ) ); wcex.cbSize = sizeof( WNDCLASSEX ); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = ( WNDPROC )WndProc; wcex.hInstance = _hInst; wcex.hCursor = LoadCursor( NULL, IDC_ARROW ); wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 ); wcex.lpszClassName = "_LANGTONS_ANT_"; RegisterClassEx( &wcex ); return CreateWindow( "_LANGTONS_ANT_", ".: Langton's Ant -- PJorente :.", WS_SYSMENU, CW_USEDEFAULT, 0, BMP_SIZE, BMP_SIZE, NULL, NULL, _hInst, NULL ); } HINSTANCE _hInst; HWND _hwnd; Ant _ant; }; int APIENTRY _tWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow ) { wnd myWnd; return myWnd.Run( hInstance ); }
c771
#include <iostream> #include <fstream> #include <string> #include <map> #include <vector> #include <algorithm> #include <iterator> int main() { std::ifstream in("unixdict.txt"); typedef std::map<std::string, std::vector<std::string> > AnagramMap; AnagramMap anagrams; std::string word; size_t count = 0; while (std::getline(in, word)) { std::string key = word; std::sort(key.begin(), key.end()); AnagramMap::mapped_type & v = anagrams[key]; v.push_back(word); count = std::max(count, v.size()); } in.close(); for (AnagramMap::const_iterator it = anagrams.begin(), e = anagrams.end(); it != e; it++) if (it->second.size() >= count) { std::copy(it->second.begin(), it->second.end(), std::ostream_iterator<std::string>(std::cout, ", ")); std::cout << std::endl; } return 0; }
c772
#include <cstdlib> void problem_occured() { std::exit(EXIT_FAILURE); }
c774
#include <iostream> #include <vector> using namespace std; int doStuff(int a, int b) { return a + b; } int main() { int t; cin >> t; vector<pair<int, int>> list(t); for(int j=0; j<t; j++){ cin >> list[j].first >> list[j].second; } cout << endl; for(int j=0;j<t;j++){ cout << doStuff(list[j].first, list[j].second) << endl;; } }
c775
inline double multiply(double a, double b) { return a*b; }
c776
#include <array> #include <iomanip> #include <iostream> const int MC = 103 * 1000 * 10000 + 11 * 9 + 1; std::array<bool, MC + 1> SV; void sieve() { std::array<int, 10000> dS; for (int a = 9, i = 9999; a >= 0; a--) { for (int b = 9; b >= 0; b--) { for (int c = 9, s = a + b; c >= 0; c--) { for (int d = 9, t = s + c; d >= 0; d--) { dS[i--] = t + d; } } } } for (int a = 0, n = 0; a < 103; a++) { for (int b = 0, d = dS[a]; b < 1000; b++, n += 10000) { for (int c = 0, s = d + dS[b] + n; c < 10000; c++) { SV[dS[c] + s++] = true; } } } } int main() { sieve(); std::cout << "The first 50 self numbers are:\n"; for (int i = 0, count = 0; count <= 50; i++) { if (!SV[i]) { count++; if (count <= 50) { std::cout << i << ' '; } else { std::cout << "\n\n Index Self number\n"; } } } for (int i = 0, limit = 1, count = 0; i < MC; i++) { if (!SV[i]) { if (++count == limit) { std::cout << std::setw(12) << count << " " << std::setw(13) << i << '\n'; limit *= 10; } } } return 0; }
c777
#include <algorithm> #include <cassert> #include <iomanip> #include <iostream> #include <vector> template <typename scalar_type> class matrix { public: matrix(size_t rows, size_t columns) : rows_(rows), columns_(columns), elements_(rows * columns) {} matrix(size_t rows, size_t columns, scalar_type value) : rows_(rows), columns_(columns), elements_(rows * columns, value) {} matrix(size_t rows, size_t columns, std::initializer_list<scalar_type> values) : rows_(rows), columns_(columns), elements_(rows * columns) { assert(values.size() <= rows_ * columns_); std::copy(values.begin(), values.end(), elements_.begin()); } size_t rows() const { return rows_; } size_t columns() const { return columns_; } scalar_type& operator()(size_t row, size_t column) { assert(row < rows_); assert(column < columns_); return elements_[row * columns_ + column]; } const scalar_type& operator()(size_t row, size_t column) const { assert(row < rows_); assert(column < columns_); return elements_[row * columns_ + column]; } private: size_t rows_; size_t columns_; std::vector<scalar_type> elements_; }; template <typename scalar_type> matrix<scalar_type> product(const matrix<scalar_type>& a, const matrix<scalar_type>& b) { assert(a.columns() == b.rows()); size_t arows = a.rows(); size_t bcolumns = b.columns(); size_t n = a.columns(); matrix<scalar_type> c(arows, bcolumns); for (size_t i = 0; i < arows; ++i) { for (size_t j = 0; j < n; ++j) { for (size_t k = 0; k < bcolumns; ++k) c(i, k) += a(i, j) * b(j, k); } } return c; } template <typename scalar_type> void swap_rows(matrix<scalar_type>& m, size_t i, size_t j) { size_t columns = m.columns(); for (size_t column = 0; column < columns; ++column) std::swap(m(i, column), m(j, column)); } template <typename scalar_type> void rref(matrix<scalar_type>& m) { size_t rows = m.rows(); size_t columns = m.columns(); for (size_t row = 0, lead = 0; row < rows && lead < columns; ++row, ++lead) { size_t i = row; while (m(i, lead) == 0) { if (++i == rows) { i = row; if (++lead == columns) return; } } swap_rows(m, i, row); if (m(row, lead) != 0) { scalar_type f = m(row, lead); for (size_t column = 0; column < columns; ++column) m(row, column) /= f; } for (size_t j = 0; j < rows; ++j) { if (j == row) continue; scalar_type f = m(j, lead); for (size_t column = 0; column < columns; ++column) m(j, column) -= f * m(row, column); } } } template <typename scalar_type> matrix<scalar_type> inverse(const matrix<scalar_type>& m) { assert(m.rows() == m.columns()); size_t rows = m.rows(); matrix<scalar_type> tmp(rows, 2 * rows, 0); for (size_t row = 0; row < rows; ++row) { for (size_t column = 0; column < rows; ++column) tmp(row, column) = m(row, column); tmp(row, row + rows) = 1; } rref(tmp); matrix<scalar_type> inv(rows, rows); for (size_t row = 0; row < rows; ++row) { for (size_t column = 0; column < rows; ++column) inv(row, column) = tmp(row, column + rows); } return inv; } template <typename scalar_type> void print(std::ostream& out, const matrix<scalar_type>& m) { size_t rows = m.rows(), columns = m.columns(); out << std::fixed << std::setprecision(4); for (size_t row = 0; row < rows; ++row) { for (size_t column = 0; column < columns; ++column) { if (column > 0) out << ' '; out << std::setw(7) << m(row, column); } out << '\n'; } } int main() { matrix<double> m(3, 3, {2, -1, 0, -1, 2, -1, 0, -1, 2}); std::cout << "Matrix:\n"; print(std::cout, m); auto inv(inverse(m)); std::cout << "Inverse:\n"; print(std::cout, inv); std::cout << "Product of matrix and inverse:\n"; print(std::cout, product(m, inv)); std::cout << "Inverse of inverse:\n"; print(std::cout, inverse(inv)); return 0; }
c778
#include <iostream> #include <functional> #include <vector> int main() { std::vector<std::function<int()> > funcs; for (int i = 0; i < 10; i++) funcs.push_back([=]() { return i * i; }); for ( std::function<int( )> f : funcs ) std::cout << f( ) << std::endl ; return 0; }
c779
#include <iostream> #include <numeric> #include <sstream> #include <vector> class Frac { public: Frac(long n, long d) { if (d == 0) { throw new std::runtime_error("d must not be zero"); } long nn = n; long dd = d; if (nn == 0) { dd = 1; } else if (dd < 0) { nn = -nn; dd = -dd; } long g = abs(std::gcd(nn, dd)); if (g > 1) { nn /= g; dd /= g; } num = nn; denom = dd; } Frac operator-() const { return Frac(-num, denom); } Frac operator+(const Frac& rhs) const { return Frac(num*rhs.denom + denom * rhs.num, rhs.denom*denom); } Frac operator-(const Frac& rhs) const { return Frac(num*rhs.denom - denom * rhs.num, rhs.denom*denom); } Frac operator*(const Frac& rhs) const { return Frac(num*rhs.num, denom*rhs.denom); } bool operator==(const Frac& rhs) const { return num == rhs.num && denom == rhs.denom; } bool operator!=(const Frac& rhs) const { return num != rhs.num || denom != rhs.denom; } bool operator<(const Frac& rhs) const { if (denom == rhs.denom) { return num < rhs.num; } return num * rhs.denom < rhs.num * denom; } friend std::ostream& operator<<(std::ostream&, const Frac&); static Frac ZERO() { return Frac(0, 1); } static Frac ONE() { return Frac(1, 1); } private: long num; long denom; }; std::ostream & operator<<(std::ostream & os, const Frac &f) { if (f.num == 0 || f.denom == 1) { return os << f.num; } std::stringstream ss; ss << f.num << "/" << f.denom; return os << ss.str(); } Frac bernoulli(int n) { if (n < 0) { throw new std::runtime_error("n may not be negative or zero"); } std::vector<Frac> a; for (int m = 0; m <= n; m++) { a.push_back(Frac(1, m + 1)); for (int j = m; j >= 1; j--) { a[j - 1] = (a[j - 1] - a[j]) * Frac(j, 1); } } if (n != 1) return a[0]; return -a[0]; } int binomial(int n, int k) { if (n < 0 || k < 0 || n < k) { throw new std::runtime_error("parameters are invalid"); } if (n == 0 || k == 0) return 1; int num = 1; for (int i = k + 1; i <= n; i++) { num *= i; } int denom = 1; for (int i = 2; i <= n - k; i++) { denom *= i; } return num / denom; } void faulhaber(int p) { using namespace std; cout << p << " : "; auto q = Frac(1, p + 1); int sign = -1; for (int j = 0; j < p + 1; j++) { sign *= -1; auto coeff = q * Frac(sign, 1) * Frac(binomial(p + 1, j), 1) * bernoulli(j); if (coeff == Frac::ZERO()) { continue; } if (j == 0) { if (coeff == -Frac::ONE()) { cout << "-"; } else if (coeff != Frac::ONE()) { cout << coeff; } } else { if (coeff == Frac::ONE()) { cout << " + "; } else if (coeff == -Frac::ONE()) { cout << " - "; } else if (coeff < Frac::ZERO()) { cout << " - " << -coeff; } else { cout << " + " << coeff; } } int pwr = p + 1 - j; if (pwr > 1) { cout << "n^" << pwr; } else { cout << "n"; } } cout << endl; } int main() { for (int i = 0; i < 10; i++) { faulhaber(i); } return 0; }
c780
#include <iostream> #include <vector> #include <string> #include <set> #include <cctype> typedef std::pair<char,char> item_t; typedef std::vector<item_t> list_t; bool can_make_word(const std::string& w, const list_t& vals) { std::set<uint32_t> used; while (used.size() < w.size()) { const char c = toupper(w[used.size()]); uint32_t x = used.size(); for (uint32_t i = 0, ii = vals.size(); i < ii; ++i) { if (used.find(i) == used.end()) { if (toupper(vals[i].first) == c || toupper(vals[i].second) == c) { used.insert(i); break; } } } if (x == used.size()) break; } return used.size() == w.size(); } int main() { list_t vals{ {'B','O'}, {'X','K'}, {'D','Q'}, {'C','P'}, {'N','A'}, {'G','T'}, {'R','E'}, {'T','G'}, {'Q','D'}, {'F','S'}, {'J','W'}, {'H','U'}, {'V','I'}, {'A','N'}, {'O','B'}, {'E','R'}, {'F','S'}, {'L','Y'}, {'P','C'}, {'Z','M'} }; std::vector<std::string> words{"A","BARK","BOOK","TREAT","COMMON","SQUAD","CONFUSE"}; for (const std::string& w : words) { std::cout << w << ": " << std::boolalpha << can_make_word(w,vals) << ".\n"; } }
c781
#include <string> #include <iostream> #include "Poco/SHA1Engine.h" #include "Poco/DigestStream.h" using Poco::DigestEngine ; using Poco::SHA1Engine ; using Poco::DigestOutputStream ; int main( ) { std::string myphrase ( "Rosetta Code" ) ; SHA1Engine sha1 ; DigestOutputStream outstr( sha1 ) ; outstr << myphrase ; outstr.flush( ) ; const DigestEngine::Digest& digest = sha1.digest( ) ; std::cout << myphrase << " as a sha1 digest :" << DigestEngine::digestToHex( digest ) << " !" << std::endl ; return 0 ; }
c782
#include <gmpxx.h> int N{123456}; mpz_class hyp[N-3]; const mpz_class G(const int n,const int g){return g>n?0:(g==1 or n-g<2)?1:hyp[n-g-2];}; void G_hyp(const int n){for(int i=0;i<N-2*n-1;i++) n==1?hyp[n-1+i]=1+G(i+n+1,n+1):hyp[n-1+i]+=G(i+n+1,n+1);} }
c783
#include <iostream> #include <string> #include <climits> using namespace std; class BalancedTernary { protected: string value; int charToInt(char c) const { if (c == '0') return 0; return 44 - c; } string negate(string s) const { for (int i = 0; i < s.length(); ++i) { if (s[i] == '+') s[i] = '-'; else if (s[i] == '-') s[i] = '+'; } return s; } public: BalancedTernary() { value = "0"; } BalancedTernary(string s) { value = string(s.rbegin(), s.rend()); } BalancedTernary(long long n) { if (n == 0) { value = "0"; return; } bool neg = n < 0; if (neg) n = -n; value = ""; while (n != 0) { int r = n % 3; if (r == 0) value += "0"; else if (r == 1) value += "+"; else { value += "-"; ++n; } n /= 3; } if (neg) value = negate(value); } BalancedTernary(const BalancedTernary &n) { value = n.value; } BalancedTernary operator+(BalancedTernary n) const { n += *this; return n; } BalancedTernary& operator+=(const BalancedTernary &n) { static char *add = "0+-0+-0"; static char *carry = "--000++"; int lastNonZero = 0; char c = '0'; for (int i = 0; i < value.length() || i < n.value.length(); ++i) { char a = i < value.length() ? value[i] : '0'; char b = i < n.value.length() ? n.value[i] : '0'; int sum = charToInt(a) + charToInt(b) + charToInt(c) + 3; c = carry[sum]; if (i < value.length()) value[i] = add[sum]; else value += add[sum]; if (add[sum] != '0') lastNonZero = i; } if (c != '0') value += c; else value = value.substr(0, lastNonZero + 1); return *this; } BalancedTernary operator-() const { BalancedTernary result; result.value = negate(value); return result; } BalancedTernary operator-(const BalancedTernary &n) const { return operator+(-n); } BalancedTernary& operator-=(const BalancedTernary &n) { return operator+=(-n); } BalancedTernary operator*(BalancedTernary n) const { n *= *this; return n; } BalancedTernary& operator*=(const BalancedTernary &n) { BalancedTernary pos = *this; BalancedTernary neg = -pos; value = "0"; for (int i = 0; i < n.value.length(); ++i) { if (n.value[i] == '+') operator+=(pos); else if (n.value[i] == '-') operator+=(neg); pos.value = '0' + pos.value; neg.value = '0' + neg.value; } return *this; } friend ostream& operator<<(ostream &out, const BalancedTernary &n) { out << n.toString(); return out; } string toString() const { return string(value.rbegin(), value.rend()); } long long toInt() const { long long result = 0; for (long long i = 0, pow = 1; i < value.length(); ++i, pow *= 3) result += pow * charToInt(value[i]); return result; } bool tryInt(long long &out) const { long long result = 0; bool ok = true; for (long long i = 0, pow = 1; i < value.length() && ok; ++i, pow *= 3) { if (value[i] == '+') { ok &= LLONG_MAX - pow >= result; result += pow; } else if (value[i] == '-') { ok &= LLONG_MIN + pow <= result; result -= pow; } } if (ok) out = result; return ok; } }; int main() { BalancedTernary a("+-0++0+"); BalancedTernary b(-436); BalancedTernary c("+-++-"); cout << "a = " << a << " = " << a.toInt() << endl; cout << "b = " << b << " = " << b.toInt() << endl; cout << "c = " << c << " = " << c.toInt() << endl; BalancedTernary d = a * (b - c); cout << "a * (b - c) = " << d << " = " << d.toInt() << endl; BalancedTernary e("+++++++++++++++++++++++++++++++++++++++++"); long long n; if (e.tryInt(n)) cout << "e = " << e << " = " << n << endl; else cout << "e = " << e << " is too big to fit in a long long" << endl; return 0; }
c784
#include <iostream> #include <vector> __int128 imax(__int128 a, __int128 b) { if (a > b) { return a; } return b; } __int128 ipow(__int128 b, __int128 n) { if (n == 0) { return 1; } if (n == 1) { return b; } __int128 res = b; while (n > 1) { res *= b; n--; } return res; } __int128 imod(__int128 m, __int128 n) { __int128 result = m % n; if (result < 0) { result += n; } return result; } bool valid(__int128 n) { if (n < 0) { return false; } while (n > 0) { int r = n % 10; if (r > 1) { return false; } n /= 10; } return true; } __int128 mpm(const __int128 n) { if (n == 1) { return 1; } std::vector<__int128> L(n * n, 0); L[0] = 1; L[1] = 1; __int128 m, k, r, j; m = 0; while (true) { m++; if (L[(m - 1) * n + imod(-ipow(10, m), n)] == 1) { break; } L[m * n + 0] = 1; for (k = 1; k < n; k++) { L[m * n + k] = imax(L[(m - 1) * n + k], L[(m - 1) * n + imod(k - ipow(10, m), n)]); } } r = ipow(10, m); k = imod(-r, n); for (j = m - 1; j >= 1; j--) { if (L[(j - 1) * n + k] == 0) { r = r + ipow(10, j); k = imod(k - ipow(10, j), n); } } if (k == 1) { r++; } return r / n; } std::ostream& operator<<(std::ostream& os, __int128 n) { char buffer[64]; int pos = (sizeof(buffer) / sizeof(char)) - 1; bool negative = false; if (n < 0) { negative = true; n = -n; } buffer[pos] = 0; while (n > 0) { int rem = n % 10; buffer[--pos] = rem + '0'; n /= 10; } if (negative) { buffer[--pos] = '-'; } return os << &buffer[pos]; } void test(__int128 n) { __int128 mult = mpm(n); if (mult > 0) { std::cout << n << " * " << mult << " = " << (n * mult) << '\n'; } else { std::cout << n << "(no solution)\n"; } } int main() { int i; for (i = 1; i <= 10; i++) { test(i); } for (i = 95; i <= 105; i++) { test(i); } test(297); test(576); test(594); test(891); test(909); test(999); test(1998); test(2079); test(2251); test(2277); test(2439); test(2997); test(4878); return 0; }
c785
#include <iostream> bool isPrime(uint64_t n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; if (n % 3 == 0) return n == 3; uint64_t test = 5; while (test * test < n) { if (n % test == 0) return false; test += 2; if (n % test == 0) return false; test += 4; } return true; } int main() { uint64_t base = 2; for (int pow = 1; pow <= 32; pow++) { if (isPrime(base - 1)) { std::cout << "2 ^ " << pow << " - 1\n"; } base *= 2; } return 0; }
c786
#include <cstdint> #include <functional> #include <iomanip> #include <iostream> uint32_t hpo2(uint32_t n) { return n & -n; } uint32_t lhpo2(uint32_t n) { uint32_t q = 0, m = hpo2(n); for (; m % 2 == 0; m >>= 1, ++q) {} return q; } uint32_t nimsum(uint32_t x, uint32_t y) { return x ^ y; } uint32_t nimprod(uint32_t x, uint32_t y) { if (x < 2 || y < 2) return x * y; uint32_t h = hpo2(x); if (x > h) return nimprod(h, y) ^ nimprod(x ^ h, y); if (hpo2(y) < y) return nimprod(y, x); uint32_t xp = lhpo2(x), yp = lhpo2(y); uint32_t comp = xp & yp; if (comp == 0) return x * y; h = hpo2(comp); return nimprod(nimprod(x >> h, y >> h), 3 << (h - 1)); } void print_table(uint32_t n, char op, std::function<uint32_t(uint32_t, uint32_t)> func) { std::cout << ' ' << op << " |"; for (uint32_t a = 0; a <= n; ++a) std::cout << std::setw(3) << a; std::cout << "\n--- -"; for (uint32_t a = 0; a <= n; ++a) std::cout << "---"; std::cout << '\n'; for (uint32_t b = 0; b <= n; ++b) { std::cout << std::setw(2) << b << " |"; for (uint32_t a = 0; a <= n; ++a) std::cout << std::setw(3) << func(a, b); std::cout << '\n'; } } int main() { print_table(15, '+', nimsum); printf("\n"); print_table(15, '*', nimprod); const uint32_t a = 21508, b = 42689; std::cout << '\n'; std::cout << a << " + " << b << " = " << nimsum(a, b) << '\n'; std::cout << a << " * " << b << " = " << nimprod(a, b) << '\n'; return 0; }
c787
#include <iostream> #include <vector> int main(int argc, char* argv[]) { std::vector<char> ls(3); ls[0] = 'a'; ls[1] = 'b'; ls[2] = 'c'; std::vector<char> us(3); us[0] = 'A'; us[1] = 'B'; us[2] = 'C'; std::vector<int> ns(3); ns[0] = 1; ns[1] = 2; ns[2] = 3; std::vector<char>::const_iterator lIt = ls.begin(); std::vector<char>::const_iterator uIt = us.begin(); std::vector<int>::const_iterator nIt = ns.begin(); for(; lIt != ls.end() && uIt != us.end() && nIt != ns.end(); ++lIt, ++uIt, ++nIt) { std::cout << *lIt << *uIt << *nIt << "\n"; } }
c788
#include <iostream> template< class T > class D3Vector { template< class U > friend std::ostream & operator<<( std::ostream & , const D3Vector<U> & ) ; public : D3Vector( T a , T b , T c ) { x = a ; y = b ; z = c ; } T dotproduct ( const D3Vector & rhs ) { T scalar = x * rhs.x + y * rhs.y + z * rhs.z ; return scalar ; } D3Vector crossproduct ( const D3Vector & rhs ) { T a = y * rhs.z - z * rhs.y ; T b = z * rhs.x - x * rhs.z ; T c = x * rhs.y - y * rhs.x ; D3Vector product( a , b , c ) ; return product ; } D3Vector triplevec( D3Vector & a , D3Vector & b ) { return crossproduct ( a.crossproduct( b ) ) ; } T triplescal( D3Vector & a, D3Vector & b ) { return dotproduct( a.crossproduct( b ) ) ; } private : T x , y , z ; } ; template< class T > std::ostream & operator<< ( std::ostream & os , const D3Vector<T> & vec ) { os << "( " << vec.x << " , " << vec.y << " , " << vec.z << " )" ; return os ; } int main( ) { D3Vector<int> a( 3 , 4 , 5 ) , b ( 4 , 3 , 5 ) , c( -5 , -12 , -13 ) ; std::cout << "a . b : " << a.dotproduct( b ) << "\n" ; std::cout << "a x b : " << a.crossproduct( b ) << "\n" ; std::cout << "a . b x c : " << a.triplescal( b , c ) << "\n" ; std::cout << "a x b x c : " << a.triplevec( b , c ) << "\n" ; return 0 ; }
c789
struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; ListNode* Solution::detectCycle(ListNode* A) { ListNode* slow = A; ListNode* fast = A; ListNode* cycleNode = 0; while (slow && fast && fast->next) { slow = slow->next; fast = fast->next->next; if (slow == fast) { cycleNode = slow; break; } } if (cycleNode == 0) { return 0; } std::set<ListNode*> setPerimeter; setPerimeter.insert(cycleNode); for (ListNode* pNode = cycleNode->next; pNode != cycleNode; pNode = pNode->next) setPerimeter.insert(pNode); for (ListNode* pNode = A; true; pNode = pNode->next) { std::set<ListNode*>::iterator iter = setPerimeter.find(pNode); if (iter != setPerimeter.end()) { return pNode; } } }
c790
template <class T> int binsearch(const T array[], int low, int high, T value) { if (high < low) { return -1; } auto mid = (low + high) / 2; if (value < array[mid]) { return binsearch(array, low, mid - 1, value); } else if (value > array[mid]) { return binsearch(array, mid + 1, high, value); } return mid; } #include <iostream> int main() { int array[] = {2, 3, 5, 6, 8}; int result1 = binsearch(array, 0, sizeof(array)/sizeof(int), 4), result2 = binsearch(array, 0, sizeof(array)/sizeof(int), 8); if (result1 == -1) std::cout << "4 not found!" << std::endl; else std::cout << "4 found at " << result1 << std::endl; if (result2 == -1) std::cout << "8 not found!" << std::endl; else std::cout << "8 found at " << result2 << std::endl; return 0; }
c791
#include <string> #include <iostream> #include <algorithm> template<typename char_type> std::basic_string<char_type> collapse(std::basic_string<char_type> str) { auto i = std::unique(str.begin(), str.end()); str.erase(i, str.end()); return str; } void test(const std::string& str) { std::cout << "original string: <<<" << str << ">>>, length = " << str.length() << '\n'; std::string collapsed(collapse(str)); std::cout << "result string: <<<" << collapsed << ">>>, length = " << collapsed.length() << '\n'; std::cout << '\n'; } int main(int argc, char** argv) { test(""); test("\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln "); test("..1111111111111111111111111111111111111111111111111111111111111117777888"); test("I never give 'em hell, I just tell the truth, and they think it's hell. "); test(" --- Harry S Truman "); return 0; }
c793
#include <string> #include <iostream> #include <boost/algorithm/string.hpp> #include <map> #include <algorithm> #include <cctype> using namespace boost::algorithm; bool isValid(const std::string &ibanstring) { static std::map<std::string, int> countrycodes { {"AL", 28}, {"AD", 24}, {"AT", 20}, {"AZ", 28 }, {"BE", 16}, {"BH", 22}, {"BA", 20}, {"BR", 29 }, {"BG", 22}, {"CR", 21}, {"HR", 21}, {"CY", 28 }, {"CZ", 24}, {"DK", 18}, {"DO", 28}, {"EE", 20 }, {"FO", 18}, {"FI", 18}, {"FR", 27}, {"GE", 22 }, {"DE", 22}, {"GI", 23}, {"GR", 27}, {"GL", 18 }, {"GT", 28}, {"HU", 28}, {"IS", 26}, {"IE", 22 }, {"IL", 23}, {"IT", 27}, {"KZ", 20}, {"KW", 30 }, {"LV", 21}, {"LB", 28}, {"LI", 21}, {"LT", 20 }, {"LU", 20}, {"MK", 19}, {"MT", 31}, {"MR", 27 }, {"MU", 30}, {"MC", 27}, {"MD", 24}, {"ME", 22 }, {"NL", 18}, {"NO", 15}, {"PK", 24}, {"PS", 29 }, {"PL", 28}, {"PT", 25}, {"RO", 24}, {"SM", 27 }, {"SA", 24}, {"RS", 22}, {"SK", 24}, {"SI", 19 }, {"ES", 24}, {"SE", 24}, {"CH", 21}, {"TN", 24 }, {"TR", 26}, {"AE", 23}, {"GB", 22}, {"VG", 24 } }; std::string teststring(ibanstring); erase_all(teststring, " "); if (countrycodes.find(teststring.substr(0, 2)) == countrycodes.end()) return false; if (teststring.length() != countrycodes[teststring.substr(0, 2)]) return false; if (!all(teststring, is_alnum())) return false; to_upper(teststring); std::rotate(teststring.begin(), teststring.begin() + 4, teststring.end()); std::string numberstring; for (const auto &c : teststring) { if (std::isdigit(c)) numberstring += c; if (std::isupper(c)) numberstring += std::to_string(static_cast<int>(c) - 55); } int segstart = 0; int step = 9; std::string prepended; long number = 0; while (segstart < numberstring.length() - step) { number = std::stol(prepended + numberstring.substr(segstart, step)); int remainder = number % 97; prepended = std::to_string(remainder); if (remainder < 10) prepended = "0" + prepended; segstart = segstart + step; step = 7; } number = std::stol(prepended + numberstring.substr(segstart)); return (number % 97 == 1); } void SayValidity(const std::string &iban) { std::cout << iban << (isValid(iban) ? " is " : " is not ") << "valid\n"; } int main() { SayValidity("GB82 WEST 1234 5698 7654 32"); SayValidity("GB82TEST12345698765432"); return 0; }
c794
#include <iostream> #include <ranges> int main() { const int maxSquareDiff = 1000; auto squareCheck = [maxSquareDiff](int i){return 2 * i - 1 > maxSquareDiff;}; auto answer = std::views::iota(1) | std::views::filter(squareCheck) | std::views::take(1); std::cout << answer.front() << '\n'; }
c795
#include <algorithm> #include <iostream> #include <iterator> #include <locale> #include <vector> #include "prime_sieve.hpp" const int limit1 = 1000000; const int limit2 = 10000000; class prime_info { public: explicit prime_info(int max) : max_print(max) {} void add_prime(int prime); void print(std::ostream& os, const char* name) const; private: int max_print; int count1 = 0; int count2 = 0; std::vector<int> primes; }; void prime_info::add_prime(int prime) { ++count2; if (prime < limit1) ++count1; if (count2 <= max_print) primes.push_back(prime); } void prime_info::print(std::ostream& os, const char* name) const { os << "First " << max_print << " " << name << " primes: "; std::copy(primes.begin(), primes.end(), std::ostream_iterator<int>(os, " ")); os << '\n'; os << "Number of " << name << " primes below " << limit1 << ": " << count1 << '\n'; os << "Number of " << name << " primes below " << limit2 << ": " << count2 << '\n'; } int main() { prime_sieve sieve(limit2); std::cout.imbue(std::locale("")); prime_info safe_primes(35); prime_info unsafe_primes(40); for (int p = 2; p < limit2; ++p) { if (sieve.is_prime(p)) { if (sieve.is_prime((p - 1)/2)) safe_primes.add_prime(p); else unsafe_primes.add_prime(p); } } safe_primes.print(std::cout, "safe"); unsafe_primes.print(std::cout, "unsafe"); return 0; }
c796
#include <iostream> bool is_prime(unsigned int n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; if (n % 3 == 0) return n == 3; for (unsigned int p = 5; p * p <= n; p += 4) { if (n % p == 0) return false; p += 2; if (n % p == 0) return false; } return true; } unsigned int digital_root(unsigned int n) { return n == 0 ? 0 : 1 + (n - 1) % 9; } int main() { const unsigned int from = 500, to = 1000; std::cout << "Nice primes between " << from << " and " << to << ":\n"; unsigned int count = 0; for (unsigned int n = from; n < to; ++n) { if (is_prime(digital_root(n)) && is_prime(n)) { ++count; std::cout << n << (count % 10 == 0 ? '\n' : ' '); } } std::cout << '\n' << count << " nice primes found.\n"; }
c797
#include <iostream> #include <random> #include <vector> double equalBirthdays(int nSharers, int groupSize, int nRepetitions) { std::default_random_engine generator; std::uniform_int_distribution<int> distribution(0, 364); std::vector<int> group(365); int eq = 0; for (int i = 0; i < nRepetitions; i++) { std::fill(group.begin(), group.end(), 0); for (int j = 0; j < groupSize; j++) { int day = distribution(generator); group[day]++; } if (std::any_of(group.cbegin(), group.cend(), [nSharers](int c) { return c >= nSharers; })) { eq++; } } return (100.0 * eq) / nRepetitions; } int main() { int groupEst = 2; for (int sharers = 2; sharers < 6; sharers++) { int groupSize = groupEst + 1; while (equalBirthdays(sharers, groupSize, 100) < 50.0) { groupSize++; } int inf = (int)(groupSize - (groupSize - groupEst) / 4.0f); for (int gs = inf; gs < groupSize + 999; gs++) { double eq = equalBirthdays(sharers, groupSize, 250); if (eq > 50.0) { groupSize = gs; break; } } for (int gs = groupSize - 1; gs < groupSize + 999; gs++) { double eq = equalBirthdays(sharers, gs, 50000); if (eq > 50.0) { groupEst = gs; printf("%d independant people in a group of %d share a common birthday. (%5.1f)\n", sharers, gs, eq); break; } } } return 0; }
c798
#include <iostream> #include <sstream> int main() { int num; std::istringstream("0123459") >> num; std::cout << num << std::endl; std::istringstream("0123459") >> std::dec >> num; std::cout << num << std::endl; std::istringstream("abcf123") >> std::hex >> num; std::cout << num << std::endl; std::istringstream("7651") >> std::oct >> num; std::cout << num << std::endl; return 0; }
c800
#include <iostream> #include <iomanip> #define MAX 120 using namespace std; bool is_prime(int n) { if (n < 2) return false; if (!(n % 2)) return n == 2; if (!(n % 3)) return n == 3; int d = 5; while (d *d <= n) { if (!(n % d)) return false; d += 2; if (!(n % d)) return false; d += 4; } return true; } int count_prime_factors(int n) { if (n == 1) return 0; if (is_prime(n)) return 1; int count = 0, f = 2; while (true) { if (!(n % f)) { count++; n /= f; if (n == 1) return count; if (is_prime(n)) f = n; } else if (f >= 3) f += 2; else f = 3; } } int main() { cout << "The attractive numbers up to and including " << MAX << " are:" << endl; for (int i = 1, count = 0; i <= MAX; ++i) { int n = count_prime_factors(i); if (is_prime(n)) { cout << setw(4) << i; if (!(++count % 20)) cout << endl; } } cout << endl; return 0; }
c801
#include <algorithm> #include <iostream> #include <map> #include <queue> #include <string> #include <vector> using namespace std; const char *men_data[][11] = { { "abe", "abi","eve","cath","ivy","jan","dee","fay","bea","hope","gay" }, { "bob", "cath","hope","abi","dee","eve","fay","bea","jan","ivy","gay" }, { "col", "hope","eve","abi","dee","bea","fay","ivy","gay","cath","jan" }, { "dan", "ivy","fay","dee","gay","hope","eve","jan","bea","cath","abi" }, { "ed", "jan","dee","bea","cath","fay","eve","abi","ivy","hope","gay" }, { "fred", "bea","abi","dee","gay","eve","ivy","cath","jan","hope","fay" }, { "gav", "gay","eve","ivy","bea","cath","abi","dee","hope","jan","fay" }, { "hal", "abi","eve","hope","fay","ivy","cath","jan","bea","gay","dee" }, { "ian", "hope","cath","dee","gay","bea","abi","fay","ivy","jan","eve" }, { "jon", "abi","fay","jan","gay","eve","bea","dee","cath","ivy","hope" } }; const char *women_data[][11] = { { "abi", "bob","fred","jon","gav","ian","abe","dan","ed","col","hal" }, { "bea", "bob","abe","col","fred","gav","dan","ian","ed","jon","hal" }, { "cath", "fred","bob","ed","gav","hal","col","ian","abe","dan","jon" }, { "dee", "fred","jon","col","abe","ian","hal","gav","dan","bob","ed" }, { "eve", "jon","hal","fred","dan","abe","gav","col","ed","ian","bob" }, { "fay", "bob","abe","ed","ian","jon","dan","fred","gav","col","hal" }, { "gay", "jon","gav","hal","fred","bob","abe","col","ed","dan","ian" }, { "hope", "gav","jon","bob","abe","ian","dan","hal","ed","col","fred" }, { "ivy", "ian","col","hal","gav","fred","bob","abe","ed","jon","dan" }, { "jan", "ed","hal","gav","abe","bob","jon","col","ian","fred","dan" } }; typedef vector<string> PrefList; typedef map<string, PrefList> PrefMap; typedef map<string, string> Couples; bool prefers(const PrefList &prefer, const string &first, const string &second) { for (PrefList::const_iterator it = prefer.begin(); it != prefer.end(); ++it) { if (*it == first) return true; if (*it == second) return false; } return false; } void check_stability(const Couples &engaged, const PrefMap &men_pref, const PrefMap &women_pref) { cout << "Stablility:\n"; bool stable = true; for (Couples::const_iterator it = engaged.begin(); it != engaged.end(); ++it) { const string &bride = it->first; const string &groom = it->second; const PrefList &preflist = men_pref.at(groom); for (PrefList::const_iterator it = preflist.begin(); it != preflist.end(); ++it) { if (*it == bride) break; if (prefers(preflist, *it, bride) && prefers(women_pref.at(*it), groom, engaged.at(*it))) { cout << "\t" << *it << " prefers " << groom << " over " << engaged.at(*it) << " and " << groom << " prefers " << *it << " over " << bride << "\n"; stable = false; } } } if (stable) cout << "\t(all marriages stable)\n"; } int main() { PrefMap men_pref, women_pref; queue<string> bachelors; for (int i = 0; i < 10; ++i) { for (int j = 1; j < 11; ++j) { men_pref[ men_data[i][0]].push_back( men_data[i][j]); women_pref[women_data[i][0]].push_back(women_data[i][j]); } bachelors.push(men_data[i][0]); } Couples engaged; cout << "Matchmaking:\n"; while (!bachelors.empty()) { const string &suitor = bachelors.front(); const PrefList &preflist = men_pref[suitor]; for (PrefList::const_iterator it = preflist.begin(); it != preflist.end(); ++it) { const string &bride = *it; if (engaged.find(bride) == engaged.end()) { cout << "\t" << bride << " and " << suitor << "\n"; engaged[bride] = suitor; break; } const string &groom = engaged[bride]; if (prefers(women_pref[bride], suitor, groom)) { cout << "\t" << bride << " dumped " << groom << " for " << suitor << "\n"; bachelors.push(groom); engaged[bride] = suitor; break; } } bachelors.pop(); } cout << "Engagements:\n"; for (Couples::const_iterator it = engaged.begin(); it != engaged.end(); ++it) { cout << "\t" << it->first << " and " << it->second << "\n"; } check_stability(engaged, men_pref, women_pref); cout << "Perturb:\n"; std::swap(engaged["abi"], engaged["bea"]); cout << "\tengage abi with " << engaged["abi"] << " and bea with " << engaged["bea"] << "\n"; check_stability(engaged, men_pref, women_pref); }
c802
#include <iostream> const char *CREATURES[] = { "fly", "spider", "bird", "cat", "dog", "goat", "cow", "horse" }; const char *COMMENTS[] = { "I don't know why she swallowed that fly.\nPerhaps she'll die\n", "That wiggled and jiggled and tickled inside her", "How absurd, to swallow a bird", "Imagine that. She swallowed a cat", "What a hog to swallow a dog", "She just opened her throat and swallowed that goat", "I don't know how she swallowed that cow", "She's dead of course" }; int main() { auto max = sizeof(CREATURES) / sizeof(char*); for (size_t i = 0; i < max; ++i) { std::cout << "There was an old lady who swallowed a " << CREATURES[i] << '\n'; std::cout << COMMENTS[i] << '\n'; for (int j = i; j > 0 && i < max - 1; --j) { std::cout << "She swallowed the " << CREATURES[j] << " to catch the " << CREATURES[j - 1] << '\n'; if (j == 1) std::cout << COMMENTS[j - 1] << '\n'; } } return 0; }
c803
#define _USE_MATH_DEFINES #include <math.h> #include <iostream> const static double EarthRadiusKm = 6372.8; inline double DegreeToRadian(double angle) { return M_PI * angle / 180.0; } class Coordinate { public: Coordinate(double latitude ,double longitude):myLatitude(latitude), myLongitude(longitude) {} double Latitude() const { return myLatitude; } double Longitude() const { return myLongitude; } private: double myLatitude; double myLongitude; }; double HaversineDistance(const Coordinate& p1, const Coordinate& p2) { double latRad1 = DegreeToRadian(p1.Latitude()); double latRad2 = DegreeToRadian(p2.Latitude()); double lonRad1 = DegreeToRadian(p1.Longitude()); double lonRad2 = DegreeToRadian(p2.Longitude()); double diffLa = latRad2 - latRad1; double doffLo = lonRad2 - lonRad1; double computation = asin(sqrt(sin(diffLa / 2) * sin(diffLa / 2) + cos(latRad1) * cos(latRad2) * sin(doffLo / 2) * sin(doffLo / 2))); return 2 * EarthRadiusKm * computation; } int main() { Coordinate c1(36.12, -86.67); Coordinate c2(33.94, -118.4); std::cout << "Distance = " << HaversineDistance(c1, c2) << std::endl; return 0; }
c804
#include <iostream> #include <gmpxx.h> static bool is_mersenne_prime(mpz_class p) { if( 2 == p ) return true; else { mpz_class s(4); mpz_class div( (mpz_class(1) << p.get_ui()) - 1 ); for( mpz_class i(3); i <= p; ++i ) { s = (s * s - mpz_class(2)) % div ; } return ( s == mpz_class(0) ); } } int main() { mpz_class maxcount(45); mpz_class found(0); mpz_class check(0); for( mpz_nextprime(check.get_mpz_t(), check.get_mpz_t()); found < maxcount; mpz_nextprime(check.get_mpz_t(), check.get_mpz_t())) { if( is_mersenne_prime(check) ) { ++found; std::cout << "M" << check << " " << std::flush; } } }
c805
#include <boost/filesystem/operations.hpp> #include <ctime> #include <iostream> int main( int argc , char *argv[ ] ) { if ( argc != 2 ) { std::cerr << "Error! Syntax: moditime <filename>!\n" ; return 1 ; } boost::filesystem::path p( argv[ 1 ] ) ; if ( boost::filesystem::exists( p ) ) { std::time_t t = boost::filesystem::last_write_time( p ) ; std::cout << "On " << std::ctime( &t ) << " the file " << argv[ 1 ] << " was modified the last time!\n" ; std::cout << "Setting the modification time to now:\n" ; std::time_t n = std::time( 0 ) ; boost::filesystem::last_write_time( p , n ) ; t = boost::filesystem::last_write_time( p ) ; std::cout << "Now the modification time is " << std::ctime( &t ) << std::endl ; return 0 ; } else { std::cout << "Could not find file " << argv[ 1 ] << '\n' ; return 2 ; } }
c806
#include <algorithm> #include <iostream> #include <numeric> #include <vector> void polyRegression(const std::vector<int>& x, const std::vector<int>& y) { int n = x.size(); std::vector<int> r(n); std::iota(r.begin(), r.end(), 0); double xm = std::accumulate(x.begin(), x.end(), 0.0) / x.size(); double ym = std::accumulate(y.begin(), y.end(), 0.0) / y.size(); double x2m = std::transform_reduce(r.begin(), r.end(), 0.0, std::plus<double>{}, [](double a) {return a * a; }) / r.size(); double x3m = std::transform_reduce(r.begin(), r.end(), 0.0, std::plus<double>{}, [](double a) {return a * a * a; }) / r.size(); double x4m = std::transform_reduce(r.begin(), r.end(), 0.0, std::plus<double>{}, [](double a) {return a * a * a * a; }) / r.size(); double xym = std::transform_reduce(x.begin(), x.end(), y.begin(), 0.0, std::plus<double>{}, std::multiplies<double>{}); xym /= fmin(x.size(), y.size()); double x2ym = std::transform_reduce(x.begin(), x.end(), y.begin(), 0.0, std::plus<double>{}, [](double a, double b) { return a * a * b; }); x2ym /= fmin(x.size(), y.size()); double sxx = x2m - xm * xm; double sxy = xym - xm * ym; double sxx2 = x3m - xm * x2m; double sx2x2 = x4m - x2m * x2m; double sx2y = x2ym - x2m * ym; double b = (sxy * sx2x2 - sx2y * sxx2) / (sxx * sx2x2 - sxx2 * sxx2); double c = (sx2y * sxx - sxy * sxx2) / (sxx * sx2x2 - sxx2 * sxx2); double a = ym - b * xm - c * x2m; auto abc = [a, b, c](int xx) { return a + b * xx + c * xx*xx; }; std::cout << "y = " << a << " + " << b << "x + " << c << "x^2" << std::endl; std::cout << " Input Approximation" << std::endl; std::cout << " x y y1" << std::endl; auto xit = x.cbegin(); auto xend = x.cend(); auto yit = y.cbegin(); auto yend = y.cend(); while (xit != xend && yit != yend) { printf("%2d %3d %5.1f\n", *xit, *yit, abc(*xit)); xit = std::next(xit); yit = std::next(yit); } } int main() { using namespace std; vector<int> x(11); iota(x.begin(), x.end(), 0); vector<int> y{ 1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321 }; polyRegression(x, y); return 0; }
c807
#include <iostream> #include <cstdlib> #include <ctime> int randint(int n) { return (1.0*n*std::rand())/(1.0+RAND_MAX); } int other(int doorA, int doorB) { int doorC; if (doorA == doorB) { doorC = randint(2); if (doorC >= doorA) ++doorC; } else { for (doorC = 0; doorC == doorA || doorC == doorB; ++doorC) { } } return doorC; } int check(int games, bool change) { int win_count = 0; for (int game = 0; game < games; ++game) { int const winning_door = randint(3); int const original_choice = randint(3); int open_door = other(original_choice, winning_door); int const selected_door = change? other(open_door, original_choice) : original_choice; if (selected_door == winning_door) ++win_count; } return win_count; } int main() { std::srand(std::time(0)); int games = 10000; int wins_stay = check(games, false); int wins_change = check(games, true); std::cout << "staying: " << 100.0*wins_stay/games << "%, changing: " << 100.0*wins_change/games << "%\n"; }
c808
using namespace System; using namespace System::Drawing; using namespace System::Windows::Forms; [STAThreadAttribute] int main() { Point^ MousePoint = gcnew Point(); Control^ TempControl = gcnew Control(); MousePoint = TempControl->MousePosition; Bitmap^ TempBitmap = gcnew Bitmap(1,1); Graphics^ g = Graphics::FromImage(TempBitmap); g->CopyFromScreen((Point)MousePoint, Point(0, 0), Size(1, 1)); Color color = TempBitmap->GetPixel(0,0); Console::WriteLine("R: "+color.R.ToString()); Console::WriteLine("G: "+color.G.ToString()); Console::WriteLine("B: "+color.B.ToString()); }
c809
#include <iostream> #include <iomanip> using namespace std; void getPrimeFactors( int li ) { int f = 2; string res; if ( li == 1 ) res = "1"; else { while ( true ) { if( !( li % f ) ) { res += to_string(f); li /= f; if( li == 1 ) break; res += " x "; } else f++; } } cout << res << "\n"; } int main( int argc, char* argv[] ) { for ( int x = 1; x < 101; x++ ) { cout << right << setw( 4 ) << x << ": "; getPrimeFactors( x ); } cout << 2144 << ": "; getPrimeFactors( 2144 ); cout << "\n\n"; return system( "pause" ); }
c810
#include <iostream> #include <fstream> #include <string> #include <tuple> #include <vector> #include <stdexcept> #include <boost/regex.hpp> struct Claim { Claim(const std::string& name) : name_(name), pro_(0), against_(0), propats_(), againstpats_() { } void add_pro(const std::string& pat) { propats_.push_back(std::make_tuple(boost::regex(pat), pat[0] == '^')); } void add_against(const std::string& pat) { againstpats_.push_back(std::make_tuple(boost::regex(pat), pat[0] == '^')); } bool plausible() const { return pro_ > against_*2; } void check(const char * buf, uint32_t len) { for (auto i = propats_.begin(), ii = propats_.end(); i != ii; ++i) { uint32_t pos = 0; boost::cmatch m; if (std::get<1>(*i) && pos > 0) continue; while (pos < len && boost::regex_search(buf+pos, buf+len, m, std::get<0>(*i))) { ++pro_; if (pos > 0) std::cerr << name_ << " [pro] multiple matches in: " << buf << "\n"; pos += m.position() + m.length(); } } for (auto i = againstpats_.begin(), ii = againstpats_.end(); i != ii; ++i) { uint32_t pos = 0; boost::cmatch m; if (std::get<1>(*i) && pos > 0) continue; while (pos < len && boost::regex_search(buf+pos, buf+len, m, std::get<0>(*i))) { ++against_; if (pos > 0) std::cerr << name_ << " [against] multiple matches in: " << buf << "\n"; pos += m.position() + m.length(); } } } friend std::ostream& operator<<(std::ostream& os, const Claim& c); private: std::string name_; uint32_t pro_; uint32_t against_; std::vector<std::tuple<boost::regex,bool>> propats_; std::vector<std::tuple<boost::regex,bool>> againstpats_; }; std::ostream& operator<<(std::ostream& os, const Claim& c) { os << c.name_ << ": matches: " << c.pro_ << " vs. counter matches: " << c.against_ << ". "; os << "Plausibility: " << (c.plausible() ? "yes" : "no") << "."; return os; } int main(int argc, char ** argv) { try { if (argc < 2) throw std::runtime_error("No input file."); std::ifstream is(argv[1]); if (! is) throw std::runtime_error("Input file not valid."); Claim ieclaim("[^c]ie"); ieclaim.add_pro("[^c]ie"); ieclaim.add_pro("^ie"); ieclaim.add_against("[^c]ei"); ieclaim.add_against("^ei"); Claim ceiclaim("cei"); ceiclaim.add_pro("cei"); ceiclaim.add_against("cie"); { const uint32_t MAXLEN = 32; char buf[MAXLEN]; uint32_t longest = 0; while (is) { is.getline(buf, sizeof(buf)); if (is.gcount() <= 0) break; else if (is.gcount() > longest) longest = is.gcount(); ieclaim.check(buf, is.gcount()); ceiclaim.check(buf, is.gcount()); } if (longest >= MAXLEN) throw std::runtime_error("Buffer too small."); } std::cout << ieclaim << "\n"; std::cout << ceiclaim << "\n"; std::cout << "Overall plausibility: " << (ieclaim.plausible() && ceiclaim.plausible() ? "yes" : "no") << "\n"; } catch (const std::exception& ex) { std::cerr << "*** Error: " << ex.what() << "\n"; return -1; } return 0; }
c811
#include <bitset> #include <iostream> #include <limits> #include <string> void print_bin(unsigned int n) { std::string str = "0"; if (n > 0) { str = std::bitset<std::numeric_limits<unsigned int>::digits>(n).to_string(); str = str.substr(str.find('1')); } std::cout << str << '\n'; } int main() { print_bin(0); print_bin(5); print_bin(50); print_bin(9000); }
c812
template<typename T> void insert_after(link<T>* list_node, link<T>* new_node) { new_node->next = list_node->next; list_node->next = new_node; };
c813
#include <iostream> #include <fstream> int main() { std::string word; std::ifstream file("unixdict.txt"); if (!file) { std::cerr << "Cannot open unixdict.txt" << std::endl; return -1; } while (file >> word) { if (word.length() > 11 && word.find("the") != std::string::npos) std::cout << word << std::endl; } return 0; }
c814
#include <iostream> #include <iomanip> #include <string> #include <cmath> #include <utility> #include <vector> using namespace std; static const double PI = acos(-1.0); double affine_remap(const pair<double, double>& from, double x, const pair<double, double>& to) { return to.first + (x - from.first) * (to.second - to.first) / (from.second - from.first); } vector<double> cheb_coef(const vector<double>& f_vals) { const int n = f_vals.size(); const double theta = PI / n; vector<double> retval(n, 0.0); for (int ii = 0; ii < n; ++ii) { double f = f_vals[ii] * 2.0 / n; const double phi = (ii + 0.5) * theta; double c1 = cos(phi), s1 = sin(phi); double c = 1.0, s = 0.0; for (int j = 0; j < n; j++) { retval[j] += f * c; const double cNext = c * c1 - s * s1; s = c * s1 + s * c1; c = cNext; } } return retval; } template<class F_> vector<double> cheb_coef(const F_& func, int n, const pair<double, double>& domain) { auto remap = [&](double x){return affine_remap({ -1.0, 1.0 }, x, domain); }; const double theta = PI / n; vector<double> fVals(n); for (int ii = 0; ii < n; ++ii) fVals[ii] = func(remap(cos((ii + 0.5) * theta))); return cheb_coef(fVals); } double cheb_eval(const vector<double>& coef, double x) { double a = 1.0, b = x, c; double retval = 0.5 * coef[0] + b * coef[1]; for (auto pc = coef.begin() + 2; pc != coef.end(); a = b, b = c, ++pc) { c = 2.0 * b * x - a; retval += (*pc) * c; } return retval; } double cheb_eval(const vector<double>& coef, const pair<double, double>& domain, double x) { return cheb_eval(coef, affine_remap(domain, x, { -1.0, 1.0 })); } struct ChebyshevApprox_ { vector<double> coeffs_; pair<double, double> domain_; double operator()(double x) const { return cheb_eval(coeffs_, domain_, x); } template<class F_> ChebyshevApprox_ (const F_& func, int n, const pair<double, double>& domain) : coeffs_(cheb_coef(func, n, domain)), domain_(domain) { } }; int main(void) { static const int N = 10; ChebyshevApprox_ fApprox(cos, N, { 0.0, 1.0 }); cout << "Coefficients: " << setprecision(14); for (const auto& c : fApprox.coeffs_) cout << "\t" << c << "\n"; for (;;) { cout << "Enter x, or non-numeric value to quit:\n"; double x; if (!(cin >> x)) return 0; cout << "True value: \t" << cos(x) << "\n"; cout << "Approximate: \t" << fApprox(x) << "\n"; } }
c815
#include <iostream> #include <numeric> #include <vector> double add_square(double prev_sum, double new_val) { return prev_sum + new_val*new_val; } double vec_add_squares(std::vector<double>& v) { return std::accumulate(v.begin(), v.end(), 0.0, add_square); } int main() { std::vector<double> v; std::cout << vec_add_squares(v) << std::endl; double data[] = { 0, 1, 3, 1.5, 42, 0.1, -4 }; v.assign(data, data+7); std::cout << vec_add_squares(v) << std::endl; return 0; }
c816
#include <iostream> #include <iomanip> #include <algorithm> #include <string> #include <set> #include <map> using namespace std; class Expression{ private: enum { NUMBER_OF_DIGITS = 9 }; enum Op { ADD, SUB, JOIN }; int code[NUMBER_OF_DIGITS]; public: static const int NUMBER_OF_EXPRESSIONS; Expression(){ for ( int i = 0; i < NUMBER_OF_DIGITS; i++ ) code[i] = ADD; } Expression& operator++(int){ for ( int i = 0; i < NUMBER_OF_DIGITS; i++ ) if ( ++code[i] > JOIN ) code[i] = ADD; else break; return *this; } operator int() const{ int value = 0, number = 0, sign = (+1); for ( int digit = 1; digit <= 9; digit++ ) switch ( code[NUMBER_OF_DIGITS - digit] ){ case ADD: value += sign*number; number = digit; sign = (+1); break; case SUB: value += sign*number; number = digit; sign = (-1); break; case JOIN: number = 10*number + digit; break; } return value + sign*number; } operator string() const{ string s; for ( int digit = 1; digit <= NUMBER_OF_DIGITS; digit++ ){ switch( code[NUMBER_OF_DIGITS - digit] ){ case ADD: if ( digit > 1 ) s.push_back('+'); break; case SUB: s.push_back('-'); break; } s.push_back('0' + digit); } return s; } }; const int Expression::NUMBER_OF_EXPRESSIONS = 2 * 3*3*3*3 * 3*3*3*3; ostream& operator<< (ostream& os, Expression& ex){ ios::fmtflags oldFlags(os.flags()); os << setw(9) << right << static_cast<int>(ex) << " = " << setw(0) << left << static_cast<string>(ex) << endl; os.flags(oldFlags); return os; } struct Stat{ map<int,int> countSum; map<int, set<int> > sumCount; Stat(){ Expression expression; for ( int i = 0; i < Expression::NUMBER_OF_EXPRESSIONS; i++, expression++ ) countSum[expression]++; for ( auto it = countSum.begin(); it != countSum.end(); it++ ) sumCount[it->second].insert(it->first); } }; void print(int givenSum){ Expression expression; for ( int i = 0; i < Expression::NUMBER_OF_EXPRESSIONS; i++, expression++ ) if ( expression == givenSum ) cout << expression; } void comment(string commentString){ cout << endl << commentString << endl << endl; } int main(){ Stat stat; comment( "Show all solutions that sum to 100" ); const int givenSum = 100; print(givenSum); comment( "Show the sum that has the maximum number of solutions" ); auto maxi = max_element(stat.sumCount.begin(),stat.sumCount.end()); auto it = maxi->second.begin(); while ( *it < 0 ) it++; cout << static_cast<int>(*it) << " has " << maxi->first << " solutions" << endl; comment( "Show the lowest positive number that can't be expressed" ); int value = 0; while(stat.countSum.count(value) != 0) value++; cout << value << endl; comment( "Show the ten highest numbers that can be expressed" ); auto rit = stat.countSum.rbegin(); for ( int i = 0; i < 10; i++, rit++ ) print(rit->first); return 0; }
c817
#include <iostream> #include <limits> int main() { float currentAverage = 0; unsigned int currentEntryNumber = 0; for (;;) { int entry; std::cout << "Enter rainfall int, 99999 to quit: "; std::cin >> entry; if (!std::cin.fail()) { if (entry == 99999) { std::cout << "User requested quit." << std::endl; break; } else { currentEntryNumber++; currentAverage = currentAverage + (1.0f/currentEntryNumber)*entry - (1.0f/currentEntryNumber)*currentAverage; std::cout << "New Average: " << currentAverage << std::endl; } } else { std::cout << "Invalid input" << std::endl; std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); } } return 0; }
c818
#include <numeric> #include <functional> int arg[] = { 1, 2, 3, 4, 5 }; int sum = std::accumulate(arg, arg+5, 0, std::plus<int>()); int prod = std::accumulate(arg, arg+5, 1, std::multiplies<int>());
c819
#include <boost/algorithm/string.hpp> #include <string> #include <iostream> int main( ) { std::string testphrase( " There are unwanted blanks here! " ) ; std::string lefttrimmed = boost::trim_left_copy( testphrase ) ; std::string righttrimmed = boost::trim_right_copy( testphrase ) ; std::cout << "The test phrase is :" << testphrase << "\n" ; std::cout << "Trimmed on the left side :" << lefttrimmed << "\n" ; std::cout << "Trimmed on the right side :" << righttrimmed << "\n" ; boost::trim( testphrase ) ; std::cout << "Trimmed on both sides :" << testphrase << "\n" ; return 0 ; }
c820
#include <iostream> using namespace std; int F(int n,int x,int y) { if (n == 0) { return x + y; } else if (y == 0) { return x; } return F(n - 1, F(n, x, y - 1), F(n, x, y - 1) + y); } int main() { cout << "F(1,3,3) = "<<F(1,3,3)<<endl; return 0; }
c821
#include <iostream> #include <string> int main( ) { std::string original ("This is the original"); std::string my_copy = original; std::cout << "This is the copy: " << my_copy << std::endl; original = "Now we change the original! "; std::cout << "my_copy still is " << my_copy << std::endl; }
c822
#include <iostream> #include <cmath> int SumDigits(const unsigned long long int digits, const int BASE = 10) { int sum = 0; unsigned long long int x = digits; for (int i = log(digits)/log(BASE); i>0; i--){ const double z = std::pow(BASE,i); const unsigned long long int t = x/z; sum += t; x -= t*z; } return x+sum; } int main() { std::cout << SumDigits(1) << ' ' << SumDigits(12345) << ' ' << SumDigits(123045) << ' ' << SumDigits(0xfe, 16) << ' ' << SumDigits(0xf0e, 16) << std::endl; return 0; }
c823
#include <array> #include <iostream> #include <string> int main() { std::array<std::string, 2> fruit { "apples", "oranges" }; std::cout << fruit.size(); return 0; }
c824
#include <algorithm> #include <iterator> #include <functional> template<class It, class Comp = std::less<>> constexpr auto max_value(It first, It last, Comp compare = std::less{}) { return *std::max_element(first, last, compare); } template<class C, class Comp = std::less<>> constexpr auto max_value(const C& container, Comp compare = std::less{}) { using std::begin; using std::end; return max_value(begin(container), end(container), compare); }
c825
#include <iostream> template<typename T> void print(T const& t) { std::cout << t; } template<typename First, typename ... Rest> void print(First const& first, Rest const& ... rest) { std::cout << first; print(rest ...); } int main() { int i = 10; std::string s = "Hello world"; print("i = ", i, " and s = \"", s, "\"\n"); }
c826
#include <iostream> int main() { std::cout << ( (727 == 0x2d7) && (727 == 01327) ? "true" : "false") << std::endl; return 0; }
c827
#include <vector> #include <memory> #include <cmath> #include <iostream> #include <iomanip> using namespace std; typedef vector< int > IntRow; typedef vector< IntRow > IntTable; auto_ptr< IntTable > getZigZagArray( int dimension ) { auto_ptr< IntTable > zigZagArrayPtr( new IntTable( dimension, IntRow( dimension ) ) ); int lastValue = dimension * dimension - 1; int currNum = 0; int currDiag = 0; int loopFrom; int loopTo; int i; int row; int col; do { if ( currDiag < dimension ) { loopFrom = 0; loopTo = currDiag; } else { loopFrom = currDiag - dimension + 1; loopTo = dimension - 1; } for ( i = loopFrom; i <= loopTo; i++ ) { if ( currDiag % 2 == 0 ) { row = loopTo - i + loopFrom; col = i; } else { row = i; col = loopTo - i + loopFrom; } ( *zigZagArrayPtr )[ row ][ col ] = currNum++; } currDiag++; } while ( currDiag <= lastValue ); return zigZagArrayPtr; } void printZigZagArray( const auto_ptr< IntTable >& zigZagArrayPtr ) { size_t dimension = zigZagArrayPtr->size(); int fieldWidth = static_cast< int >( floor( log10( static_cast< double >( dimension * dimension - 1 ) ) ) ) + 2; size_t col; for ( size_t row = 0; row < dimension; row++ ) { for ( col = 0; col < dimension; col++ ) cout << setw( fieldWidth ) << ( *zigZagArrayPtr )[ row ][ col ]; cout << endl; } } int main() { printZigZagArray( getZigZagArray( 5 ) ); }
c828
#include <cassert> #include <cstdlib> #include <iostream> #include <stdexcept> #include <utility> #include <vector> #include <libxml/parser.h> #include <libxml/tree.h> #include <libxml/xmlerror.h> #include <libxml/xmlstring.h> #include <libxml/xmlversion.h> #include <libxml/xpath.h> #ifndef LIBXML_XPATH_ENABLED # error libxml was not configured with XPath support #endif template <typename F> class [[nodiscard]] scope_exit { public: constexpr explicit scope_exit(F&& f) : f_{std::move(f)} {} ~scope_exit() { f_(); } scope_exit(scope_exit const&) = delete; scope_exit(scope_exit&&) = delete; auto operator=(scope_exit const&) -> scope_exit& = delete; auto operator=(scope_exit&&) -> scope_exit& = delete; private: F f_; }; class libxml_error : public std::runtime_error { public: libxml_error() : libxml_error(std::string{}) {} explicit libxml_error(std::string message) : std::runtime_error{make_message_(std::move(message))} {} private: static auto make_message_(std::string message) -> std::string { if (auto const last_error = ::xmlGetLastError(); last_error) { if (not message.empty()) message += ": "; message += last_error->message; } return message; } }; auto main() -> int { try { ::xmlInitParser(); LIBXML_TEST_VERSION auto const libxml_cleanup = scope_exit{[] { ::xmlCleanupParser(); }}; auto const doc = ::xmlParseFile("test.xml"); if (not doc) throw libxml_error{"failed to load document"}; auto const doc_cleanup = scope_exit{[doc] { ::xmlFreeDoc(doc); }}; auto const xpath_context = ::xmlXPathNewContext(doc); if (not xpath_context) throw libxml_error{"failed to create XPath context"}; auto const xpath_context_cleanup = scope_exit{[xpath_context] { ::xmlXPathFreeContext(xpath_context); }}; { std::cout << "Task 1:\n"; auto const xpath = reinterpret_cast<::xmlChar const*>(u8" auto xpath_obj = ::xmlXPathEvalExpression(xpath, xpath_context); if (not xpath_obj) throw libxml_error{"failed to evaluate XPath"}; auto const xpath_obj_cleanup = scope_exit{[xpath_obj] { ::xmlXPathFreeObject(xpath_obj); }}; auto const result = xmlXPathNodeSetItem(xpath_obj->nodesetval, 0); if (result) std::cout << '\t' << "node found" << '\n'; else std::cout << '\t' << "node not found" << '\n'; } { std::cout << "Task 2:\n"; auto const xpath = reinterpret_cast<::xmlChar const*>(u8" auto xpath_obj = ::xmlXPathEvalExpression(xpath, xpath_context); if (not xpath_obj) throw libxml_error{"failed to evaluate XPath"}; auto const xpath_obj_cleanup = scope_exit{[xpath_obj] { ::xmlXPathFreeObject(xpath_obj); }}; auto const count = xmlXPathNodeSetGetLength(xpath_obj->nodesetval); for (auto i = decltype(count){0}; i < count; ++i) { auto const node = xmlXPathNodeSetItem(xpath_obj->nodesetval, i); assert(node); auto const content = XML_GET_CONTENT(node); assert(content); std::cout << "\n\t" << reinterpret_cast<char const*>(content); } std::cout << '\n'; } { std::cout << "Task 3:\n"; auto const xpath = reinterpret_cast<::xmlChar const*>(u8" auto xpath_obj = ::xmlXPathEvalExpression(xpath, xpath_context); if (not xpath_obj) throw libxml_error{"failed to evaluate XPath"}; auto const xpath_obj_cleanup = scope_exit{[xpath_obj] { ::xmlXPathFreeObject(xpath_obj); }}; auto const results = [ns=xpath_obj->nodesetval]() { auto v = std::vector<::xmlNode*>{}; if (ns && ns->nodeTab) v.assign(ns->nodeTab, ns->nodeTab + ns->nodeNr); return v; }(); std::cout << '\t' << "set of " << results.size() << " node(s) found" << '\n'; } } catch (std::exception const& x) { std::cerr << "ERROR: " << x.what() << '\n'; return EXIT_FAILURE; } }
c829
#include <windows.h> #include <ctime> #include <string> const int BMP_SIZE = 600, ITERATIONS = static_cast<int>( 15e5 ); class myBitmap { public: myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {} ~myBitmap() { DeleteObject( pen ); DeleteObject( brush ); DeleteDC( hdc ); DeleteObject( bmp ); } bool create( int w, int h ) { BITMAPINFO bi; ZeroMemory( &bi, sizeof( bi ) ); bi.bmiHeader.biSize = sizeof( bi.bmiHeader ); bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8; bi.bmiHeader.biCompression = BI_RGB; bi.bmiHeader.biPlanes = 1; bi.bmiHeader.biWidth = w; bi.bmiHeader.biHeight = -h; HDC dc = GetDC( GetConsoleWindow() ); bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 ); if( !bmp ) return false; hdc = CreateCompatibleDC( dc ); SelectObject( hdc, bmp ); ReleaseDC( GetConsoleWindow(), dc ); width = w; height = h; return true; } void clear( BYTE clr = 0 ) { memset( pBits, clr, width * height * sizeof( DWORD ) ); } void setBrushColor( DWORD bClr ) { if( brush ) DeleteObject( brush ); brush = CreateSolidBrush( bClr ); SelectObject( hdc, brush ); } void setPenColor( DWORD c ) { clr = c; createPen(); } void setPenWidth( int w ) { wid = w; createPen(); } void saveBitmap( std::string path ) { BITMAPFILEHEADER fileheader; BITMAPINFO infoheader; BITMAP bitmap; DWORD wb; GetObject( bmp, sizeof( bitmap ), &bitmap ); DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight]; ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) ); ZeroMemory( &infoheader, sizeof( BITMAPINFO ) ); ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) ); infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8; infoheader.bmiHeader.biCompression = BI_RGB; infoheader.bmiHeader.biPlanes = 1; infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader ); infoheader.bmiHeader.biHeight = bitmap.bmHeight; infoheader.bmiHeader.biWidth = bitmap.bmWidth; infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ); fileheader.bfType = 0x4D42; fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER ); fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage; GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS ); HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL ); WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL ); WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL ); WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL ); CloseHandle( file ); delete [] dwpBits; } HDC getDC() const { return hdc; } int getWidth() const { return width; } int getHeight() const { return height; } private: void createPen() { if( pen ) DeleteObject( pen ); pen = CreatePen( PS_SOLID, wid, clr ); SelectObject( hdc, pen ); } HBITMAP bmp; HDC hdc; HPEN pen; HBRUSH brush; void *pBits; int width, height, wid; DWORD clr; }; class fern { public: void draw() { bmp.create( BMP_SIZE, BMP_SIZE ); float x = 0, y = 0; HDC dc = bmp.getDC(); int hs = BMP_SIZE >> 1; for( int f = 0; f < ITERATIONS; f++ ) { SetPixel( dc, hs + static_cast<int>( x * 55.f ), BMP_SIZE - 15 - static_cast<int>( y * 55.f ), RGB( static_cast<int>( rnd() * 80.f ) + 20, static_cast<int>( rnd() * 128.f ) + 128, static_cast<int>( rnd() * 80.f ) + 30 ) ); getXY( x, y ); } bmp.saveBitmap( "./bf.bmp" ); } private: void getXY( float& x, float& y ) { float g, xl, yl; g = rnd(); if( g < .01f ) { xl = 0; yl = .16f * y; } else if( g < .07f ) { xl = .2f * x - .26f * y; yl = .23f * x + .22f * y + 1.6f; } else if( g < .14f ) { xl = -.15f * x + .28f * y; yl = .26f * x + .24f * y + .44f; } else { xl = .85f * x + .04f * y; yl = -.04f * x + .85f * y + 1.6f; } x = xl; y = yl; } float rnd() { return static_cast<float>( rand() ) / static_cast<float>( RAND_MAX ); } myBitmap bmp; }; int main( int argc, char* argv[]) { srand( static_cast<unsigned>( time( 0 ) ) ); fern f; f.draw(); return 0; }
c830
#include <iostream> #include <utility> #include <complex> typedef std::complex<double> complex; std::pair<complex, complex> solve_quadratic_equation(double a, double b, double c) { b /= a; c /= a; double discriminant = b*b-4*c; if (discriminant < 0) return std::make_pair(complex(-b/2, std::sqrt(-discriminant)/2), complex(-b/2, -std::sqrt(-discriminant)/2)); double root = std::sqrt(discriminant); double solution1 = (b > 0)? (-b - root)/2 : (-b + root)/2; return std::make_pair(solution1, c/solution1); } int main() { std::pair<complex, complex> result = solve_quadratic_equation(1, -1e20, 1); std::cout << result.first << ", " << result.second << std::endl; }
c831
#include <iostream> #include <cstdint> typedef uint64_t integer; integer bit_count(integer n) { integer count = 0; for (; n > 0; count++) n >>= 1; return count; } integer mod_pow(integer p, integer n) { integer square = 1; for (integer bits = bit_count(p); bits > 0; square %= n) { square *= square; if (p & (1 << --bits)) square <<= 1; } return square; } bool is_prime(integer n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; for (integer p = 3; p * p <= n; p += 2) if (n % p == 0) return false; return true; } integer find_mersenne_factor(integer p) { for (integer k = 0, q = 1;;) { q = 2 * ++k * p + 1; if ((q % 8 == 1 || q % 8 == 7) && mod_pow(p, q) == 1 && is_prime(q)) return q; } return 0; } int main() { std::cout << find_mersenne_factor(929) << std::endl; return 0; }
c832
#include <iomanip> #include <iostream> using namespace std; const int pasTriMax = 61; uint64_t pasTri[pasTriMax + 1]; void pascalTriangle(unsigned long n) { unsigned long j, k; pasTri[0] = 1; j = 1; while (j <= n) { j++; k = j / 2; pasTri[k] = pasTri[k - 1]; for ( ;k >= 1; k--) pasTri[k] += pasTri[k - 1]; } } bool isPrime(unsigned long n) { if (n > pasTriMax) { cout << n << " is out of range" << endl; exit(1); } pascalTriangle(n); bool res = true; int i = n / 2; while (res && (i > 1)) { res = res && (pasTri[i] % n == 0); i--; } return res; } void expandPoly(unsigned long n) { const char vz[] = {'+', '-'}; if (n > pasTriMax) { cout << n << " is out of range" << endl; exit(1); } switch (n) { case 0: cout << "(x-1)^0 = 1" << endl; break; case 1: cout << "(x-1)^1 = x-1" << endl; break; default: pascalTriangle(n); cout << "(x-1)^" << n << " = "; cout << "x^" << n; bool bVz = true; int nDiv2 = n / 2; for (unsigned long j = n - 1; j > nDiv2; j--, bVz = !bVz) cout << vz[bVz] << pasTri[n - j] << "*x^" << j; for (unsigned long j = nDiv2; j > 1; j--, bVz = !bVz) cout << vz[bVz] << pasTri[j] << "*x^" << j; cout << vz[bVz] << pasTri[1] << "*x"; bVz = !bVz; cout << vz[bVz] << pasTri[0] << endl; break; } } int main() { for (unsigned long n = 0; n <= 9; n++) expandPoly(n); for (unsigned long n = 2; n <= pasTriMax; n++) if (isPrime(n)) cout << setw(3) << n; cout << endl; }
c833
#include <iostream> #include <iterator> #include <vector> #include <ppl.h> #include <concurrent_vector.h> struct Factors { int number; std::vector<int> primes; }; const int data[] = { 12757923, 12878611, 12878893, 12757923, 15808973, 15780709, 197622519 }; int main() { Concurrency::concurrent_vector<Factors> results; Concurrency::parallel_for_each(std::begin(data), std::end(data), [&](int n) { Factors factors; factors.number = n; for (int f = 2; n > 1; ++f) { while (n % f == 0) { factors.primes.push_back(f); n /= f; } } results.push_back(factors); }); auto max = std::max_element(results.begin(), results.end(), [](const Factors &a, const Factors &b) { return a.primes.front() < b.primes.front(); }); std::for_each(results.begin(), results.end(), [&](const Factors &f) { if (f.primes.front() == max->primes.front()) { std::cout << f.number << " = [ "; std::copy(f.primes.begin(), f.primes.end(), std::ostream_iterator<int>(std::cout, " ")); std::cout << "]\n"; } }); return 0; }
c834
#include <algorithm> int main() { int nums[] = {2,4,3,1,2}; std::sort(nums, nums+sizeof(nums)/sizeof(int)); return 0; }
c835
#include <iostream> #include <cryptopp/filters.h> #include <cryptopp/hex.h> #include <cryptopp/sha.h> int main(int argc, char **argv){ CryptoPP::SHA256 hash; std::string digest; std::string message = "Rosetta code"; CryptoPP::StringSource s(message, true, new CryptoPP::HashFilter(hash, new CryptoPP::HexEncoder( new CryptoPP::StringSink(digest)))); std::cout << digest << std::endl; return 0; }
c836
#include <math.h> #include <iostream> unsigned pwr[10]; unsigned munch( unsigned i ) { unsigned sum = 0; while( i ) { sum += pwr[(i % 10)]; i /= 10; } return sum; } int main( int argc, char* argv[] ) { for( int i = 0; i < 10; i++ ) pwr[i] = (unsigned)pow( (float)i, (float)i ); std::cout << "Munchausen Numbers\n==================\n"; for( unsigned i = 1; i < 5000; i++ ) if( i == munch( i ) ) std::cout << i << "\n"; return 0; }
c837
#include <bit> #include <iostream> int main() { std::cout << "int is " << sizeof(int) << " bytes\n"; std::cout << "a pointer is " << sizeof(int*) << " bytes\n\n"; if (std::endian::native == std::endian::big) { std::cout << "platform is big-endian\n"; } else { std::cout << "host is little-endian\n"; } }
c838
#include <vector> #include <iostream> #include <numeric> #include <iterator> #include <memory> #include <string> #include <algorithm> #include <iomanip> std::vector<int> nacci ( const std::vector<int> & start , int arity ) { std::vector<int> result ( start ) ; int sumstart = 1 ; while ( result.size( ) < 15 ) { if ( result.size( ) <= arity ) result.push_back( std::accumulate( result.begin( ) , result.begin( ) + result.size( ) , 0 ) ) ; else { result.push_back( std::accumulate ( result.begin( ) + sumstart , result.begin( ) + sumstart + arity , 0 )) ; sumstart++ ; } } return std::move ( result ) ; } int main( ) { std::vector<std::string> naccinames {"fibo" , "tribo" , "tetra" , "penta" , "hexa" , "hepta" , "octo" , "nona" , "deca" } ; const std::vector<int> fibo { 1 , 1 } , lucas { 2 , 1 } ; for ( int i = 2 ; i < 11 ; i++ ) { std::vector<int> numberrow = nacci ( fibo , i ) ; std::cout << std::left << std::setw( 10 ) << naccinames[ i - 2 ].append( "nacci" ) << std::setw( 2 ) << " : " ; std::copy ( numberrow.begin( ) , numberrow.end( ) , std::ostream_iterator<int>( std::cout , " " ) ) ; std::cout << "...\n" ; numberrow = nacci ( lucas , i ) ; std::cout << "Lucas-" << i ; if ( i < 10 ) std::cout << "  : " ; else std::cout << "  : " ; std::copy ( numberrow.begin( ) , numberrow.end( ) , std::ostream_iterator<int>( std::cout , " " ) ) ; std::cout << "...\n" ; } return 0 ; }
c839
#include <iostream> #include <random> std::default_random_engine generator; bool biased(int n) { std::uniform_int_distribution<int> distribution(1, n); return distribution(generator) == 1; } bool unbiased(int n) { bool flip1, flip2; do { flip1 = biased(n); flip2 = biased(n); } while (flip1 == flip2); return flip1; } int main() { for (size_t n = 3; n <= 6; n++) { int biasedZero = 0; int biasedOne = 0; int unbiasedZero = 0; int unbiasedOne = 0; for (size_t i = 0; i < 100000; i++) { if (biased(n)) { biasedOne++; } else { biasedZero++; } if (unbiased(n)) { unbiasedOne++; } else { unbiasedZero++; } } std::cout << "(N = " << n << ")\n"; std::cout << "Biased:\n"; std::cout << " 0 = " << biasedZero << "; " << biasedZero / 1000.0 << "%\n"; std::cout << " 1 = " << biasedOne << "; " << biasedOne / 1000.0 << "%\n"; std::cout << "Unbiased:\n"; std::cout << " 0 = " << unbiasedZero << "; " << unbiasedZero / 1000.0 << "%\n"; std::cout << " 1 = " << unbiasedOne << "; " << unbiasedOne / 1000.0 << "%\n"; std::cout << '\n'; } return 0; }
c840
#include <iostream> #include <vector> int main() { int numberOfLines; std::cin >> numberOfLines; std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); std::vector<std::string> lines(numberOfLines); for(int i = 0; i < numberOfLines; ++i) { std::getline(std::cin, lines[i]); } for(const auto& value : lines) { std::cout << value << "\n"; } }
c841
#include <iostream> int main() { std::cout << "Goodbye, World!"; return 0; }
c842
#include <iostream> #include <blitz/tinymat.h> int main() { using namespace blitz; TinyMatrix<double,3,3> A, B, C; A = 1, 2, 3, 4, 5, 6, 7, 8, 9; B = 1, 0, 0, 0, 1, 0, 0, 0, 1; C = product(A, B); std::cout << C << std::endl; }
c843
#include <limits> double inf() { if (std::numeric_limits<double>::has_infinity) return std::numeric_limits<double>::infinity(); else return std::numeric_limits<double>::max(); }
c844
#include <iostream> #include <vector> bool isCusip(const std::string& s) { if (s.size() != 9) return false; int sum = 0; for (int i = 0; i <= 7; ++i) { char c = s[i]; int v; if ('0' <= c && c <= '9') { v = c - '0'; } else if ('A' <= c && c <= 'Z') { v = c - '@'; } else if (c = '*') { v = 36; } else if (c = '#') { v = 38; } else { return false; } if (i % 2 == 1) { v *= 2; } sum += v / 10 + v % 10; } return s[8] - '0' == (10 - (sum % 10)) % 10; } int main() { using namespace std; vector<string> candidates{ "037833100", "17275R102", "38259P508", "594918104", "68389X106", "68389X105" }; for (auto str : candidates) { auto res = isCusip(str) ? "correct" : "incorrect"; cout << str.c_str() << " -> " << res << "\n"; } return 0; }
c845
#ifndef MYWIDGET_H #define MYWIDGET_H #include <QWidget> class QPaintEvent ; class MyWidget : public QWidget { public : MyWidget( ) ; protected : void paintEvent( QPaintEvent * ) ; } ; #endif
c846
#include <iostream> int main() { const int max_it = 13; const int max_it_j = 10; double a1 = 1.0, a2 = 0.0, d1 = 3.2; std::cout << " i d\n"; for (int i = 2; i <= max_it; ++i) { double a = a1 + (a1 - a2) / d1; for (int j = 1; j <= max_it_j; ++j) { double x = 0.0; double y = 0.0; for (int k = 1; k <= 1 << i; ++k) { y = 1.0 - 2.0*y*x; x = a - x * x; } a -= x / y; } double d = (a1 - a2) / (a - a1); printf("%2d  %.8f\n", i, d); d1 = d; a2 = a1; a1 = a; } return 0; }
c847
#include <algorithm> #include <functional> #include <iostream> #include <vector> std::vector<int> primes; struct Seq { public: bool empty() { return p < 0; } int front() { return p; } void popFront() { if (p == 2) { p++; } else { p += 2; while (!empty() && !isPrime(p)) { p += 2; } } } private: int p = 2; bool isPrime(int n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; if (n % 3 == 0) return n == 3; int d = 5; while (d * d <= n) { if (n % d == 0) return false; d += 2; if (n % d == 0) return false; d += 4; } return true; } }; void init() { Seq seq; while (!seq.empty() && primes.size() < 50000) { primes.push_back(seq.front()); seq.popFront(); } } bool findCombo(int k, int x, int m, int n, std::vector<int>& combo) { if (k >= m) { int sum = 0; for (int idx : combo) { sum += primes[idx]; } if (sum == x) { auto word = (m > 1) ? "primes" : "prime"; printf("Partitioned %5d with %2d %s ", x, m, word); for (int idx = 0; idx < m; ++idx) { std::cout << primes[combo[idx]]; if (idx < m - 1) { std::cout << '+'; } else { std::cout << '\n'; } } return true; } } else { for (int j = 0; j < n; j++) { if (k == 0 || j > combo[k - 1]) { combo[k] = j; bool foundCombo = findCombo(k + 1, x, m, n, combo); if (foundCombo) { return true; } } } } return false; } void partition(int x, int m) { if (x < 2 || m < 1 || m >= x) { throw std::runtime_error("Invalid parameters"); } std::vector<int> filteredPrimes; std::copy_if( primes.cbegin(), primes.cend(), std::back_inserter(filteredPrimes), [x](int a) { return a <= x; } ); int n = filteredPrimes.size(); if (n < m) { throw std::runtime_error("Not enough primes"); } std::vector<int> combo; combo.resize(m); if (!findCombo(0, x, m, n, combo)) { auto word = (m > 1) ? "primes" : "prime"; printf("Partitioned %5d with %2d %s: (not possible)\n", x, m, word); } } int main() { init(); std::vector<std::pair<int, int>> a{ {99809, 1}, { 18, 2}, { 19, 3}, { 20, 4}, { 2017, 24}, {22699, 1}, {22699, 2}, {22699, 3}, {22699, 4}, {40355, 3} }; for (auto& p : a) { partition(p.first, p.second); } return 0; }
c848
#include <string> #include <sstream> #include <vector> #include <iterator> #include <iostream> #include <algorithm> int main() { std::string s = "Hello,How,Are,You,Today"; std::vector<std::string> v; std::istringstream buf(s); for(std::string token; getline(buf, token, ','); ) v.push_back(token); copy(v.begin(), v.end(), std::ostream_iterator<std::string>(std::cout, ".")); std::cout << '\n'; }
c849
#include <iostream> #include <gmpxx.h> template<typename Integer, typename OutputIterator> void decompose(Integer n, OutputIterator out) { Integer i(2); while (n != 1) { while (n % i == Integer(0)) { *out++ = i; n /= i; } ++i; } } template<typename T> class infix_ostream_iterator: public std::iterator<T, std::output_iterator_tag> { class Proxy; friend class Proxy; class Proxy { public: Proxy(infix_ostream_iterator& iter): iterator(iter) {} Proxy& operator=(T const& value) { if (!iterator.first) { iterator.stream << iterator.infix; } iterator.stream << value; } private: infix_ostream_iterator& iterator; }; public: infix_ostream_iterator(std::ostream& os, char const* inf): stream(os), first(true), infix(inf) { } infix_ostream_iterator& operator++() { first = false; return *this; } infix_ostream_iterator operator++(int) { infix_ostream_iterator prev(*this); ++*this; return prev; } Proxy operator*() { return Proxy(*this); } private: std::ostream& stream; bool first; char const* infix; }; int main() { std::cout << "please enter a positive number: "; mpz_class number; std::cin >> number; if (number <= 0) std::cout << "this number is not positive!\n;"; else { std::cout << "decomposition: "; decompose(number, infix_ostream_iterator<mpz_class>(std::cout, " * ")); std::cout << "\n"; } }
c850
#include <iostream> #include <vector> #include <utility> std::vector<int> hailstone(int i) { std::vector<int> v; while(true){ v.push_back(i); if (1 == i) break; i = (i % 2) ? (3 * i + 1) : (i / 2); } return v; } std::pair<int,int> find_longest_hailstone_seq(int n) { std::pair<int, int> maxseq(0, 0); int l; for(int i = 1; i < n; ++i){ l = hailstone(i).size(); if (l > maxseq.second) maxseq = std::make_pair(i, l); } return maxseq; } int main () { std::vector<int> h27; h27 = hailstone(27); int l = h27.size(); std::cout << "length of hailstone(27) is " << l; std::cout << " first four elements of hailstone(27) are "; std::cout << h27[0] << " " << h27[1] << " " << h27[2] << " " << h27[3] << std::endl; std::cout << " last four elements of hailstone(27) are " << h27[l-4] << " " << h27[l-3] << " " << h27[l-2] << " " << h27[l-1] << std::endl; std::pair<int,int> m = find_longest_hailstone_seq(100000); std::cout << "the longest hailstone sequence under 100,000 is " << m.first << " with " << m.second << " elements." <<std::endl; return 0; }
c852
#include <iostream> #include <cmath> int main() { std::cout << "(5 ^ 3) ^ 2 = " << (uint) pow(pow(5,3), 2) << std::endl; std::cout << "5 ^ (3 ^ 2) = "<< (uint) pow(5, (pow(3, 2))); return EXIT_SUCCESS; }
c853
#include <iostream> #include <bitset> #include <string> const int ArraySize = 20; const int NumGenerations = 10; const std::string Initial = "0011101101010101001000"; int main() { std::bitset<ArraySize + 2> array(Initial); for(int j = 0; j < NumGenerations; ++j) { std::bitset<ArraySize + 2> tmpArray(array); for(int i = ArraySize; i >= 1 ; --i) { if(array[i]) std::cout << "#"; else std::cout << "_"; int val = (int)array[i-1] << 2 | (int)array[i] << 1 | (int)array[i+1]; tmpArray[i] = (val == 3 || val == 5 || val == 6); } array = tmpArray; std::cout << std::endl; } }
c854
#include <iostream> #include <chrono> #include <ctime> int main() { std::chrono::system_clock::time_point epoch; std::time_t t = std::chrono::system_clock::to_time_t(epoch); std::cout << std::asctime(std::gmtime(&t)) << '\n'; return 0; }
c855
#include <string> #include <iostream> #include <algorithm> #include <cctype> class MyTransform { private : int shift ; public : MyTransform( int s ) : shift( s ) { } char operator( )( char c ) { if ( isspace( c ) ) return ' ' ; else { static std::string letters( "abcdefghijklmnopqrstuvwxyz" ) ; std::string::size_type found = letters.find(tolower( c )) ; int shiftedpos = ( static_cast<int>( found ) + shift ) % 26 ; if ( shiftedpos < 0 ) shiftedpos = 26 + shiftedpos ; char shifted = letters[shiftedpos] ; return shifted ; } } } ; int main( ) { std::string input ; std::cout << "Which text is to be encrypted ?\n" ; getline( std::cin , input ) ; std::cout << "shift ?\n" ; int myshift = 0 ; std::cin >> myshift ; std::cout << "Before encryption:\n" << input << std::endl ; std::transform ( input.begin( ) , input.end( ) , input.begin( ) , MyTransform( myshift ) ) ; std::cout << "encrypted:\n" ; std::cout << input << std::endl ; myshift *= -1 ; std::transform ( input.begin( ) , input.end( ) , input.begin( ) , MyTransform( myshift ) ) ; std::cout << "Decrypted again:\n" ; std::cout << input << std::endl ; return 0 ; }
c856
#include <algorithm> #include <iostream> #include <utility> #include <vector> template <typename iterator> void normalize_ranges(iterator begin, iterator end) { for (iterator i = begin; i != end; ++i) { if (i->second < i->first) std::swap(i->first, i->second); } std::sort(begin, end); } template <typename iterator> iterator merge_ranges(iterator begin, iterator end) { iterator out = begin; for (iterator i = begin; i != end; ) { iterator j = i; while (++j != end && j->first <= i->second) i->second = std::max(i->second, j->second); *out++ = *i; i = j; } return out; } template <typename iterator> iterator consolidate_ranges(iterator begin, iterator end) { normalize_ranges(begin, end); return merge_ranges(begin, end); } template <typename pair> void print_range(std::ostream& out, const pair& range) { out << '[' << range.first << ", " << range.second << ']'; } template <typename iterator> void print_ranges(std::ostream& out, iterator begin, iterator end) { if (begin != end) { print_range(out, *begin++); for (; begin != end; ++begin) { out << ", "; print_range(out, *begin); } } } int main() { std::vector<std::pair<double, double>> test_cases[] = { { {1.1, 2.2} }, { {6.1, 7.2}, {7.2, 8.3} }, { {4, 3}, {2, 1} }, { {4, 3}, {2, 1}, {-1, -2}, {3.9, 10} }, { {1, 3}, {-6, -1}, {-4, -5}, {8, 2}, {-6, -6} } }; for (auto&& ranges : test_cases) { print_ranges(std::cout, std::begin(ranges), std::end(ranges)); std::cout << " -> "; auto i = consolidate_ranges(std::begin(ranges), std::end(ranges)); print_ranges(std::cout, std::begin(ranges), i); std::cout << '\n'; } return 0; }
c857
#include <array> #include <iostream> void require(bool condition, const std::string &message) { if (condition) { return; } throw std::runtime_error(message); } template<typename T, size_t N> std::ostream &operator<<(std::ostream &os, const std::array<T, N> &a) { auto it = a.cbegin(); auto end = a.cend(); os << '['; if (it != end) { os << *it; it = std::next(it); } while (it != end) { os << ", " << *it; it = std::next(it); } return os << ']'; } template <size_t RC, size_t CC> class Matrix { std::array<std::array<double, CC>, RC> data; public: Matrix() : data{} { } Matrix(std::initializer_list<std::initializer_list<double>> values) { size_t rp = 0; for (auto row : values) { size_t cp = 0; for (auto col : row) { data[rp][cp] = col; cp++; } rp++; } } double get(size_t row, size_t col) const { return data[row][col]; } void set(size_t row, size_t col, double value) { data[row][col] = value; } std::array<double, CC> get(size_t row) { return data[row]; } void set(size_t row, const std::array<double, CC> &values) { std::copy(values.begin(), values.end(), data[row].begin()); } template <size_t D> Matrix<RC, D> operator*(const Matrix<CC, D> &rhs) const { Matrix<RC, D> result; for (size_t i = 0; i < RC; i++) { for (size_t j = 0; j < D; j++) { for (size_t k = 0; k < CC; k++) { double prod = get(i, k) * rhs.get(k, j); result.set(i, j, result.get(i, j) + prod); } } } return result; } Matrix<CC, RC> transpose() const { Matrix<CC, RC> trans; for (size_t i = 0; i < RC; i++) { for (size_t j = 0; j < CC; j++) { trans.set(j, i, data[i][j]); } } return trans; } void toReducedRowEchelonForm() { size_t lead = 0; for (size_t r = 0; r < RC; r++) { if (CC <= lead) { return; } auto i = r; while (get(i, lead) == 0.0) { i++; if (RC == i) { i = r; lead++; if (CC == lead) { return; } } } auto temp = get(i); set(i, get(r)); set(r, temp); if (get(r, lead) != 0.0) { auto div = get(r, lead); for (size_t j = 0; j < CC; j++) { set(r, j, get(r, j) / div); } } for (size_t k = 0; k < RC; k++) { if (k != r) { auto mult = get(k, lead); for (size_t j = 0; j < CC; j++) { auto prod = get(r, j) * mult; set(k, j, get(k, j) - prod); } } } lead++; } } Matrix<RC, RC> inverse() { require(RC == CC, "Not a square matrix"); Matrix<RC, 2 * RC> aug; for (size_t i = 0; i < RC; i++) { for (size_t j = 0; j < RC; j++) { aug.set(i, j, get(i, j)); } aug.set(i, i + RC, 1.0); } aug.toReducedRowEchelonForm(); Matrix<RC, RC> inv; for (size_t i = 0; i < RC; i++) { for (size_t j = RC; j < 2 * RC; j++) { inv.set(i, j - RC, aug.get(i, j)); } } return inv; } template <size_t RC, size_t CC> friend std::ostream &operator<<(std::ostream &, const Matrix<RC, CC> &); }; template <size_t RC, size_t CC> std::ostream &operator<<(std::ostream &os, const Matrix<RC, CC> &m) { for (size_t i = 0; i < RC; i++) { os << '['; for (size_t j = 0; j < CC; j++) { if (j > 0) { os << ", "; } os << m.get(i, j); } os << "]\n"; } return os; } template <size_t RC, size_t CC> std::array<double, RC> multiple_regression(const std::array<double, CC> &y, const Matrix<RC, CC> &x) { Matrix<1, CC> tm; tm.set(0, y); auto cy = tm.transpose(); auto cx = x.transpose(); return ((x * cx).inverse() * x * cy).transpose().get(0); } void case1() { std::array<double, 5> y{ 1.0, 2.0, 3.0, 4.0, 5.0 }; Matrix<1, 5> x{ {2.0, 1.0, 3.0, 4.0, 5.0} }; auto v = multiple_regression(y, x); std::cout << v << '\n'; } void case2() { std::array<double, 3> y{ 3.0, 4.0, 5.0 }; Matrix<2, 3> x{ {1.0, 2.0, 1.0}, {1.0, 1.0, 2.0} }; auto v = multiple_regression(y, x); std::cout << v << '\n'; } void case3() { std::array<double, 15> y{ 52.21, 53.12, 54.48, 55.84, 57.20, 58.57, 59.93, 61.29, 63.11, 64.47, 66.28, 68.10, 69.92, 72.19, 74.46 }; std::array<double, 15> a{ 1.47, 1.50, 1.52, 1.55, 1.57, 1.60, 1.63, 1.65, 1.68, 1.70, 1.73, 1.75, 1.78, 1.80, 1.83 }; Matrix<3, 15> x; for (size_t i = 0; i < 15; i++) { x.set(0, i, 1.0); } x.set(1, a); for (size_t i = 0; i < 15; i++) { x.set(2, i, a[i] * a[i]); } auto v = multiple_regression(y, x); std::cout << v << '\n'; } int main() { case1(); case2(); case3(); return 0; }
c858
#include <iostream> int main() { int Base = 10; const int N = 2; int c1 = 0; int c2 = 0; for (int k=1; k<pow((double)Base,N); k++){ c1++; if (k%(Base-1) == (k*k)%(Base-1)){ c2++; std::cout << k << " "; } } std::cout << "\nTrying " << c2 << " numbers instead of " << c1 << " numbers saves " << 100 - ((double)c2/c1)*100 << "%" <<std::endl; return 0; }
c859
#include <iostream> struct link { link* next; int data; link(int newItem, link* head) : next{head}, data{newItem}{} }; void PrintList(link* head) { if(!head) return; std::cout << head->data << " "; PrintList(head->next); } link* RemoveItem(int valueToRemove, link*&head) { for(link** node = &head; *node; node = &((*node)->next)) { if((*node)->data == valueToRemove) { link* removedNode = *node; *node = removedNode->next; removedNode->next = nullptr; return removedNode; } } return nullptr; } int main() { link link33{33, nullptr}; link link42{42, &link33}; link link99{99, &link42}; link link55{55, &link99}; link* head = &link55; std::cout << "Full list: "; PrintList(head); std::cout << "\nRemove 55: "; auto removed = RemoveItem(55, head); PrintList(head); std::cout << "\nThe removed item: "; PrintList(removed); std::cout << "\nTry to remove -3: "; auto removed2 = RemoveItem(-3, head); PrintList(head); if (!removed2) std::cout << "\nItem not found\n"; }