Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I'm new to C++.
So I found this reverse code on the internet. My prof. told me to make a palindrome checker, so I look for the reverse first.
Here is what I made
void main()
{
int num;
int new_num = 0;
int dummy;
cout << "Masukkan angka";
cin >> num;
dummy = num;
cout << dummy << endl;
while (num > 0)
{
new_num = new_num*10 + (num % 10);
num = num/10;
}
cout << new_num << endl;
if ( new_num == dummy)
{
cout << "true";
}
else
cout<<"false";
getch();
}
The most confusing part is this
while(num > 0)
{
new_num = new_num*10 + (num % 10);
num = num/10;
}
cout << new_num << endl;
I found this on the internet and I don't know how it works.
Can someone explain how this code can reverse the number I input? Like when I input 12345, the output would be 54321. I can't understand.
Its talking the last char of your input by using modulo.
input is: 12345
Cycle 1:
new_num is 0, multiply by 10 give 0.
add modulo or your input 12345 % 10 = 5, new_num is now 5.
divide your input by 10 to remove last digit. input = 1234
Cycle 2,3,4 etc.:
new_num is 5, multiply by 10 gives 50.
add modulo or your input 1234 % 10 = 4, new_num is now 54.
divide your input by 10 to remove last digit. input = 123
I have taken the liberty to modify your source, and provide it in a more readable format
int inputNumber = 123;
int reversedNumber = 0;
cout << "The input number is " << inputNumber << endl;
while (inputNumber > 0) {
reversedNumber = reversedNumber*10 + inputNumber%10;
inputNumber = inputNumber/10;
}
cout << "The reversed number is " << reversedNumber << endl;
First of all, always use meaningful variables.
It will be more helpful while reading your code.
Now on to the explanation,
The modulo operator gives the remainder (not quotient!) of a division,
i.e. 5%2 = 1.
In the while loop,
1) We keep over-writing reversedNumber by changing (increasing) its decimal position (multiply by 10) and adding the remainder of the division of inputNumber and 10
2) We over-write reversedNumber by changing (decreasing) its decimal position (divide by 10).
I encourage you to actually trace out the program on paper, or printing the variable's values (debugging?) to see how this operation works.
First take a look at what num % 10 does:
#include <iostream>
int main() {
for (int i = 0; i < 100; ++i) {
std::cout << i << " % 10 = " << i % 10 << '\n';
}
}
http://coliru.stacked-crooked.com/a/8d26b893682b0001
Do you see the pattern? This expression basically just gets the least significant decimal digit from a number.
You should know the pattern in new_num*10 without even looking, since we learned this in elementary school math: It shifts the digits to the left one place.
Then if you think about what addition will do in this case, new_num*10 + num % 10, you should see that adding a number in the range [0..9] to an integer where the lowest digit is zero, will just replace that zero with the new digit.
num/10 shifts digits to the right, and since it's using integral division the fractional parts are discarded.
So all together we have:
int remove_last_digit(int value) { return value / 10; }
int get_last_digit(int value) { return value % 10; }
int push_digit(int value, int digit) {
return value * 10 + digit;
}
bool has_more_digits(int value) { return value != 0; }
int reverse_int(int value) {
int reversed_value = 0;
while ( has_more_digits(value)) {
reversed_value = push_digit(reversed_value, get_last_digit(value));
value = remove_last_digit(value);
}
return reversed_value;
}
Think of a number as digits piled on top of each other. If you take the top digit and put it on top of a second pile, and keep doing that until the first pile is empty, then the digits in the second pile are now stacked in the reverse order.
Related
I am trying to take a user entered integer (positive or negative) and let them pick a digit position and output the digit at that position.
int findDigAtPos(int number)
{
int position;
int result;
cout << "Enter digit position between 1 and " << std::to_string(number).length() << endl;
cin >> position;
while (position < 0 || position > std::to_string(number).length())
{
cout << "Enter digit position between 1 and "<< std::to_string(number).length()<<endl;
cin >> position;
}
if (std::to_string(number).length() == 1)
cout << "Only one digit" << endl;
number = number / pow(10, (position - 1.0));
result = number % 10;
return result;
}
This is the code I currently have for the function. However, it outputs the number in reverse. How do I correct the digit position? I thought it didn't even function correctly until noticing it's in reverse order.
First, note that you shouldn't be using the pow function when working with integers, because it returns a double result, which can cause problems due to unexpected truncation of the result.
But, if you insist on using it, then you need to remember that the power of 10 by which to divide will decrease as the digit position increases: i.e., the position is given with the leftmost (most significant) digit in position 1. Thus, that power of 10 will be total number of digits minus the position:
number = number / pow(10, (std::to_string(number).length() - position));
result = number % 10;
The safer method (not using pow) would be a small loop, like this:
for (int d = std::to_string(number).length() - position; d > 0; --d) number /= 10;
result = number % 10;
However, as you're already converting the passed number to a string, then why not just save that string and extract the digit from it – at position-1, because array (and string) indexes in C++ are zero-based:
int findDigAtPos(int number)
{
int position;
std::string str = std::to_string(std::abs(number)); // If -ve, remove sign!
int ndig = str.length();
std::cout << "Enter digit position between 1 and " << ndig << "\n";
std::cin >> position;
while (position < 0 || position > ndig) {
std::cout << "Enter digit position between 1 and " << ndig << "\n";
std::cin >> position;
}
return str.at(position-1) - '0';
}
Note that the codes (ASCII or otherwise) for the numeric digits, 0 thru 9 are guaranteed by the C++ standard to be contiguous and in order, so subtracting the value of the digit 0 will 'convert' any digit to its actual, numerical value.
Instead of this:
number = number / pow(10, (position - 1.0));
result = number % 10;
This:
int length = (int)(std::to_string(number).length());
while (position < length)
{
number = number / 10;
length--;
}
result = number % 10;
The above should work fine for positive numbers. For negative numbers, you might need to a fixup. I'll leave that as an exercise for you to manage.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
So, i was given an assignment to find 20 odd numbers starting from a number entered by user.. I know how to find odd numbers. but I don't know how to find them starting from a number entered by user.
I tried this:
#include<iostream>
using namespace std;
int main(){
int num,i;
cout<<"Enter num: ";
cin>>num;
for(i=num;i<=20;i++){
if(i%2!=0)
cout<<num <<endl;
}
}
but it outputs the number entered by user 20 times.
As the comment says, you output the num, not newly calculated i, but even if you fix that, you will output only few odd numbers (or none), for example for input 50 there will be no output instead of odd 20 numbers (because 50 <= 20 is always false, so no for body will be executed). Plus you are doing lot of math... while the whole task can collapse to trivial:
#include<iostream>
int main() {
int num;
std::cout << "Enter num: ";
std::cin >> num;
num |= 1; // turn user number into odd one (if it was even)
const int endNum = num + 20*2; // calculate the first odd number after 20 of them (end value)
while (num < endNum) {
std::cout << num << std::endl;
num += 2;
}
}
doing just simple addition +2 in loop.
edit: btw, why num |= 1; guarantees odd number... because integers in computer are stored as binary values, where every digit is different power of two, with the least significant bit corresponding to the zeroth power of two (i.e. value 1). If this bit is set, then the value is odd, because dividing by two does apply from first power of two upward and this bottom bit is remainder. And if it is reset, the value is even, for the same reason, the bottom bit is remainder after you would divide the value by two. The binary or operator |= 1 will set the least significant bit to one, turning any integer value to odd one.
This is the special case, when your task involves calculation based on powers of two. Because all the values in computer are already encoded in the binary way, there are usually shortcuts how to get the result of such calculation. Like for example to get remainder of division by 16 from integer n you can do binary and: n & 15 and you have the remainder. Or to divide by 16 you can shift the unsigned integer value by four bits to the right like n >> 4 to get the result. But this doesn't work with calculations which are not power-of-two based, i.e. remainder after dividing by ten is NOT n & 9, because 9 is 0b1001, so different values will be trimmed down to only values 0, 1, 8 or 9, but remainders after dividing by 10 can be any value from 0 to 9. .. while 15 is in binary 0b1111, so such binary and-mask will produce all values from 0 to 15, and they correspond to the remainder by div 16.
The bug in your code is that you print num instead of i. So just do:
cout<< i <<endl;
^
But you can simplify your code a lot by doing:
#include<iostream>
using namespace std;
int main(){
int num,i;
cout<<"Enter num: ";
cin>>num;
if (num%2 == 0) ++num; // Make sure num is odd
for(i=0; i < 20; ++i){ // Print 20 numbers
cout << (num + 2*i) << endl; // Multiply i by 2 and add it to num
// so that the result is the next odd number
}
}
note
As suggested by Ped7g the line
if (num%2 == 0) ++num; // Make sure num is odd
can be made more simple. Just replace it with
num |= 1; // Set the least significant bit so that num is odd
This loop
for(i=num;i<=20;i++){
if(i%2!=0)
cout<<num <<endl;
}
does not make sense because it checks the variable i instead of the variable num whether it is an odd number. And it is obvious there will be outputted a half of 20 values of i.
The program can look the following way
#include <iostream>
int main()
{
const size_t N = 20;
int n = 0;
std::cout << "Enter a number: ";
std::cin >> n;
n |= 1; // make the first odd number
for ( size_t i = 0; i < N; i++ )
{
std::cout << n << ' ';
n += 2;
}
}
Its output might look the following way
Enter a number: 10
11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49
A more correct professional code can look the following way
#include <iostream>
#include <limits>
int main()
{
const size_t N = 20;
int n = 0;
std::cout << "Enter a number: ";
std::cin >> n;
n |= 1;
for ( size_t i = 0; i < N; i++ )
{
std::cout << n << ' ';
n = std::numeric_limits<int>::max() - 2 < n ? std::numeric_limits<int>::min() | 1 : n + 2;
}
}
In this case if the user will enter the maximum integer value then the output will look like
Enter a number: 2147483647
2147483647 -2147483647 -2147483645 -2147483643 -2147483641 -2147483639 -2147483637 -2147483635 -2147483633 -2147483631 -2147483629 -2147483627 -2147483625 -2147483623 -2147483621 -2147483619 -2147483617 -2147483615 -2147483613 -2147483611
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
#include
using namespace std;
int main()
{
int n, i;
cout << "Enter a positive integer: ";
cin >> n;
cout << "Factors of " << n << " are: " << endl;
for(i = 1; i <= n; ++i)
{
if(n % i == 0)
cout << i << endl;
}
return 0;
}
I understand the below problem of finding factors of numbers. But i want to do a c++ program which only show the numbers which have 5 or more factors. suppose i give a range of numbers 15 to 20.then it will print only those numbers those have 5 or more factors. such as example if i give a range 15 to 20 then it will print out only 16,18,20.because these 3 integers have 5 or more factors in 15 to 20 range. i couldnt understand how to do that code so i am asking.
As I understood you are searching the tech finding number prime factors of an natural number. Firstly the code you published is for getting all the divisor's of given positive number. But Finding its prime factors a little bit different but the idea same as you used (modular arithmetic)
this is a very simple version of achieving your task (but needs optimization)
#include <iostream>
//This function does not handle the repeating factors count
int numberOfPrimeFactors(int number) {
int count = 0;
for ( int i = 2; i <= number; ++i ) {
while ( number % i == 0 ) {
number /= i;
count++;
}
}
return count;
}
int main() {
int Rbegin = 1;
int Rend = 100;
for(int i = Rbegin; i<Rend; ++i) {
if(numberOfPrimeFactors(i) >= 5)
std::cout << i << " has 5 or more prime factor"<< std::endl;
}
}
I'm trying a lab exercise which wants user to input a 2 4-digit integer. Then the program will extract all the numbers in the 4-digit integer and use the number to do an arithmetic calculation just like the image link below.
Arithmetic Calculation with 2 4-digit integer
However, the objective for this lab exercise is not to allow me myself, to use a for loop to obtain the result.
For instance, when i want to obtain the last number of the 4 digit integer, I could easily do it by using this.
int firstDigit = firstNo % 10; //i will get 4 if the integer is 1234
int secondDigit = secondNo % 10; //i will get 8 if the integer is 5678
And of course table formatting is nothing to worry about before getting the logic right. Next is a very simple calculation of the numbers using the digit i obtain from the above.
int addfirstNumbers = firstDigit + secondDigit;
int minusfirstNumbers = firstDigit - secondDigit;
int multiplefirstNumbers = firstDigit * secondDigit;
int modfirstNumbers = firstDigit % secondDigit;
double divfirstNumbers = firstDigit / secondDigit;
cout << "add: " << addfirstNumbers << endl
<< "minus " << minusfirstNumbers << endl
<< "multipile " << multiplefirstNumbers << endl
<< "remainder " << modfirstNumbers << endl
<< "division " << divfirstNumbers << endl;
I do understand forloop can make my life easier. But i'm just trying out the long method before trying out the shorter way which is forloop.
But even before i proceed, I'm still unable to extract out the other digit from this 4 digit integer.
Like Mike Vine mentioned in the comments, you can do integer division before taking the modulo.
#include <iostream>
int main(){
int x = 1234;
std::cout << (x/10)%10 << "\n";
}
#Output
3
Edit: This works for all places of a number. To find the nth value from the end, just keep adding 0s to the divisor. For example to find the 2nd from the last, you'd want to divide x by 100 instead.
You could simply do
int secondLastDigit = ((i - (i % 10)) % 100)) / 10;
For i=5678:
i % 10 (5678 % 10) equals 8
i - (i % 10) (5678 - 8) therefore equals 5670.
(i - (i % 10)) % 100 (5670 % 100) equals 70
Finally (i - (i % 10)) % 100) / 10 (70 / 10) = 7
This is pretty simple, just use the modulus operator on the number for 100(num%100), getting the last two digits that way, and then divide that result by ten, and store the digit in an int (so the decimal is properly truncated.)
Im having trouble with the function taylor2 not returning a value if i input anything over 2. If I enter 0-2 it outputs the correct value but anything over 2 and I just get a flashing underscore with no data returned.
void taylor2(double x)
{
double total = 1;
int i = 0;
int count = 1;
double temp = 1;
do
{
{
if (i % 2 == 1)
{
temp = (pow(x, i * 2 + 2) / factorial(i * 2 + 2));
total += temp;
}
else {
temp = (pow(x, i * 2 + 2) / factorial(i * 2 + 2));
total -= temp;
}
}
count++;
i++;
} while (fabs(temp) >= .0001);
cout << "The last recoreded temporary value was: "<<temp << endl;
cout << "The computed value for cosine is : "<< total << endl;
cout << "It took " <<count << " values to calculate the value of the function to .0001 places"<< endl;
cout << endl;
}
I suspect that factorial is returning an int. If int is 32 bit (very common), then factorial will overflow once the argument reaches 13 (i = 5 in your case). Signed integer overflow is undefined behaviour in C++.
You could use a std::uint64_t (an unsigned 64 bit integer). This will allow you to evaluate a few larger factorials.
For more reference, see Calculating large factorials in C++
Better still, use a recurrence relation between your Taylor terms.