Problem: Find the highest place value exponent in a Base-10 integer.
Pre-requisite: i.e. 9,448,320,743 You may say, what does the 9 represent? (billion) what does the 4 next to the 9 represent? (hundred million) what number is in the hundred thousand's place?(3)
Base-10 123456 number is written as 1(100,000)+2(10000)+3(1000)+4(100)+5(10)+6(1) and that is 1(10^5)+2(10^4)+3(10^3)+4(10^2)+5(10^1)+6(10^0)
Analysis: In order to find the largest place value, we need to find the largest exponent of base 10.
We can find the highest exponent if we divide the integer by 10^exp where exp = {0,1,2,3,...}
i.e. 46578
num | exp | 10exp | num/10exp |
123456 | 0 | 1 | 123456 |
1 | 10 | 12345 | |
2 | 100 | 1234 | |
3 | 1000 | 123 | |
4 | 10000 | 12 | |
5 | 100000 | 1 | |
6 | 1000000 | 0 | |
7 | 10000000 | 0 |
Design: Design involves creating a pseudo code or flow chart in order to develop the algorithm.
start
output "Welcome"
output "Enter a number"
input as num
if input not a number then
output "Error: Better luck next time."
return 1
endif
call findExp use num
output "The exponent in: "
output "Thanks for using my program."
stop
start findExp reference myNum
call abs using myNum as myNum
declare exp = 0
while myNum / 10^exp > 10 then
exp=exp+1
endhile
myNum = exp
return
Code: Now, that we have the basic idea, you can pick the language and code the problem.
#include<iostream>
#include<cmath>
using namespace std;
void findExp(int& num);
int main(){
int num,exp;
cout << "Welcome" << endl;
cout << "Enter a number: ";
cin >> num;
if (!cin){ //validating user input
cout << "Error: Better luck next time." << endl;
return 1;
}
findExp(num); //function call
cout << "The exponent in: " << num << endl;
cout << "Thanks for using my program." << endl;
return 0;
}
void findExp(int& myNum){
myNum = abs(myNum);
int exp = 0;
while (myNum / pow(10, exp) > 10){
exp++;
}
myNum= exp; //setting the new value to the referenced value
}
No comments:
Post a Comment