From f0711c0b7bc0ecb9e5be538fee1d478ec0589fa8 Mon Sep 17 00:00:00 2001 From: ericdouglas Date: Mon, 1 Jun 2015 12:20:24 -0300 Subject: [PATCH] cube root of a perfect cube --- .../src/02-lecture.js | 85 +++++++++++++------ 1 file changed, 60 insertions(+), 25 deletions(-) diff --git a/computer-science/01-introduction-to-cs-and-programming-mit/src/02-lecture.js b/computer-science/01-introduction-to-cs-and-programming-mit/src/02-lecture.js index b247eaa..f837cf2 100644 --- a/computer-science/01-introduction-to-cs-and-programming-mit/src/02-lecture.js +++ b/computer-science/01-introduction-to-cs-and-programming-mit/src/02-lecture.js @@ -53,39 +53,74 @@ var prompt = require( 'prompt' ); // }); -// Find the lowest among three numbers +// // Find the lowest among three numbers +// prompt.start(); +// prompt.get([ +// { +// name : 'x', +// description : 'Enter x' +// }, +// { +// name : 'y', +// description : 'Enter y' +// }, +// { +// name : 'z', +// description : 'Enter z' +// } +// ], function( err, results ) { + +// if ( results.x < results.y ) { + +// if ( results.x < results.z ) { +// console.log( 'x is least' ); +// } else { +// console.log( 'z is least' ); +// } + +// } else if ( results.y < results.z ) { + +// console.log( 'y is least' ); + +// } else { + +// console.log( 'z is least' ); + +// } + +// }); + +// Find the cube root of a perfect cube prompt.start(); prompt.get([ { - name : 'x', - description : 'Enter x' - }, - { - name : 'y', - description : 'Enter y' - }, - { - name : 'z', - description : 'Enter z' + name : 'x', + description : 'Enter a interger' } ], function( err, results ) { - if ( results.x < results.y ) { + var x = parseInt( results.x, 10 ); + var ans = 0; - if ( results.x < results.z ) { - console.log( 'x is least' ); - } else { - console.log( 'z is least' ); - } + while ( Math.pow( ans, 3 ) < Math.abs( x )) { - } else if ( results.y < results.z ) { - - console.log( 'y is least' ); - - } else { - - console.log( 'z is least' ); + ans += 1; + console.log( 'Current guess:', ans ); } -}); + if ( Math.pow( ans, 3 ) !== Math.abs( x )) { + + console.log( x, 'is not a perfect cube' ); + + } else { + + if ( x < 0 ) { + ans = -ans; + } + + console.log( 'Cube root of ' + x.toString() + ' is ' + ans.toString()); + + } + +}); \ No newline at end of file