From 193cf97fb78400ef9659a67f506cec6b1179c40e Mon Sep 17 00:00:00 2001 From: Mohammad S Anwar Date: Tue, 4 Jan 2022 22:23:00 +0000 Subject: - Added solutions by Ulrich Rieke. --- challenge-146/ulrich-rieke/cpp/ch-2.cpp | 70 +++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 challenge-146/ulrich-rieke/cpp/ch-2.cpp (limited to 'challenge-146/ulrich-rieke/cpp/ch-2.cpp') diff --git a/challenge-146/ulrich-rieke/cpp/ch-2.cpp b/challenge-146/ulrich-rieke/cpp/ch-2.cpp new file mode 100644 index 0000000000..e9d58c88d8 --- /dev/null +++ b/challenge-146/ulrich-rieke/cpp/ch-2.cpp @@ -0,0 +1,70 @@ +#include +#include +#include +#include + +std::pair createParent( int dividend , int divisor , int bdividend , + int bdivisor ) { + std::pair node ; + double product = ( (static_cast( dividend ) / + static_cast( divisor )) * + ( static_cast( bdividend ) / static_cast(bdivisor))) ; + int firstMin = std::min( dividend, divisor ) ; + int secondMin = std::min( bdividend, bdivisor ) ; + if ( product > 1.0 ) { + node = std::make_pair( std::max( firstMin , secondMin ) , + std::min( firstMin, secondMin ) ) ; + } + if ( product < 1.0 ) { + node = std::make_pair( std::min( firstMin , secondMin ) , + std::max( firstMin, secondMin ) ) ; + } + if ( product == 1.0 ) + node = std::make_pair( 1 , 1 ) ; + return node ; +} + +std::pair createBrother( int dividend , int divisor ) { + int maximum = std::max( dividend , divisor ) ; + int minimum = std::min( dividend, divisor ) ; + if ( maximum == dividend ) { + return std::make_pair( maximum - minimum , maximum ) ; + } + else { + return std::make_pair( maximum , maximum - minimum ) ; + } +} + +int main( ) { + std::cout << "Enter a fraction as dividend/divisor!\n" ; + std::string input ; + std::cin >> input ; + std::string::size_type found = input.find( "/" ) ; + while ( found == std::string::npos ) { + std::cout << "Please enter a fraction as dividend/divisor!\n" ; + std::cin >> input ; + found = input.find( "/" ) ; + } + int howmany = static_cast( found ) ; + int dividend = std::stoi( input.substr( 0 , howmany ) ) ; + int divisor = std::stoi( input.substr( howmany + 1 ) ) ; + if ( dividend == 1 && divisor == 1 ) + std::cout << "parent = and grandparent = " << std::endl ; + else { + double fraction = static_cast( dividend ) / static_cast( divisor) ; + if ( fraction == 0.5 || fraction == 2.0 ) + std::cout << "parent = 1/1 and grandparent = !" << std::endl ; + else { + std::pair brother = createBrother( dividend , divisor ) ; + std::pair parent = createParent( dividend, divisor , brother.first , + brother.second ) ; + std::pair uncle = createBrother( parent.first , parent.second ) ; + std::pair grandParent = createParent( parent.first , parent.second , + uncle.first , uncle.second ) ; + std::cout << "parent = " << parent.first << '/' << parent.second ; + std::cout << " and grandparent = " << grandParent.first << '/' << + grandParent.second << std::endl ; + } + } + return 0 ; +} -- cgit