So I wrote this small application that will convert a decimal to octal, and it is outputting the right answer only it's backwards. An example would be that if the answer to the conversion was 17, the application would display it as 71.
Any help would be much appreciated.
;
int _tmain(int argc, _TCHAR* argv[])
{
int octal, total = 0;
cout<< "please enter a decimal: ";
cin >> octal;
while(octal > 0)
{
total = octal % 8;
octal /= 8;
cout << total;
}
cout << endl;
_getche();
return 0;
}
You can use std::oct to print number in octal notation.
int n = 123;
std::cout << std::oct << n << std::endl;
Similarly you can print number in different notations like decimal - std::dec and hexadecimal - std::hex.
Those input/output manipulators allow user to parse string numbers in various notations.
int n;
std::istringstream("24") >> std::hex >> n;
std::cout << n << std::endl; // n is 36 (decimal)
You need to take a sum and then print the final result, something like
int n=0;
while (octal > 0) {
total += (pow(10,n++))*(octal % 8);
octal /= 8;
}
cout << total << endl;
Just printing the digits will print them in reverse order since you are printing the smallest bits first.
As noted in the comments, the mechanism above will only work for converting to bases smaller than 10.
You are doing fine but you have to print the remainders in reverse order to get the correct answer . For e.g. if ans is 17 then decimal equivalent will be 1*8^1+7*8^0 . unit digit will be the remainder obtained by dividing the number by 8 , next digit to the left will be the remainder obtained by dividing the number by 8^2 and so on. So if the number in octal is of n digit then the most significant digit will be the remainder obtained by dividing the number by 8^n.That is why you have to print the remainder in reverse order.
A solution using an array for temporary storage:
int octal, total = 0, length=0;
char storage[12]; /* 11 octal digits add up to > 1 billion */
octal = 123;
while (octal > 0)
{
storage[length] = octal % 8;
octal /= 8;
length++;
}
while (--length >= 0)
printf ("%d", storage[length]);
printf ("\n");
(I happened to be in C mode, hence the printfs. Change to cout where required.)
The most important point is that you are bound by the storage size. You can set it to a reasonable size -- the largest positive octal size you can put in an integer is 017777777777 --, and even an unreasonable size is acceptable (you can set it to 20, which will only waste 8 additional bytes; these days, that's nothing). The storage size is determined by how big the representation of your number is in octal, for the largest number you can enter.
Suppose you change both 8s to 2; then you can use this same routine for binary output. But at that point, the number of output characters increases to 31! (One less than the [likely] number of bits in your int, because the last bit would toggle the number to negative. You need separate code to handle negative numbers.)
It works as-is for all bases <=10 (including "base 10" itself). If you want to extend the same code to handle bases >10, such as "duodecimal" (base 12) or hexadecimal (base 16), you need to change the printf line. This will make your code work up to base 36 ("sexatrigesimal"). Per convention, "digits" higher than 9 are written A,B,C and so on:
while (--length >= 0)
printf ("%c", storage[length] < 10 ? storage[length]+'0' : storage[length]+'A'-10);
(As I'm making this up as I write, I used the ternary operator ?..:.. for convenience, rather than a separate if..else, which needs more typing. (OTOH, adding the comment negates the gain. Oh well -- at least you learned about the ternary operator, as well as the names for a couple of number bases.))
Another solution is to use recursion. This is a useful method because it doesn't need to preallocate some space in memory -- instead, it relies on the internal call stack.
The principle is that you write a function that only prints the last digit of your number -- but before it does that, unless the remainder is 0, it calls itself with the remainder of the number.
So the function calls itself, then prints the number it should. Because it first calls itself, the called version prints the number it should -- the one to the left of the digit in the "original" function. And so on and so forth, until there is no digit remaining to be printed. From that point on, the last called function prints its number (which is the leftmost digit), returns to the function it was called from, which in turn prints its number (one more to the right), all the way down to the original call.
Recursion is a pretty cool skill to master, so do try this!
Here are two handy functions which might be useful. They return string for each of the conversions. On similar lines to igleyy's answer.
string toOctalFromDecimal (int num) {
ostringstream o;
o << std::oct << num;
return o.str();
}
string toDecimalFromOctal (int num) {
std::ostringstream o;
int x;
std::istringstream(to_string(num)) >> std::oct >> x;
o << std::dec << x;
return o.str();
}
Related
I'm trying to write a program that uses the series to compute the value of PI. The user will input how far it wants the program to compute the series and then the program should output its calculated value of PI. I believe I've successfully written the code for this, however it does not do well with large numbers and only gives me a few decimal places. When I tried to use cout << fixed << setprecision(42); It just gave me "nan" as the value of PI.
int main() {
long long seqNum; // sequence number users will input
long double val; // the series output
cout << "Welcome to the compute PI program." << endl; // welcome message
cout << "Please inter the sequence number in the form of an integer." << endl;
cin >> seqNum; // user input
while ( seqNum < 0) // validation, number must be positive
{
cout << "Please enter a positive number." << endl;
cin >> seqNum;
} // end while
if (seqNum > 0)
{
for ( long int i = 0; i < seqNum; i++ )
{
val = val + 4*(pow(-1.00,i)/(1 + 2*i)); // Gregory-Leibniz sum calculation
}// end for
cout << val;
} // end if
return 0;
}
Any help would be really appreciated. Thank you
Your problem involves an elementary, fundamental principle related to double values: a double, or any floating point type, can hold only a fixed upper limit of significant digits. There is no unlimited digits of precision with plain, garden-variety doubles. There's a hard, upper limit. The exact limit is implementation defined, but on modern C++ implementations the typical limit is just 16 or 17 digits of precision, not even close to your desired 42 digits of precision.
#include <limits>
#include <iostream>
int main()
{
std::cout << std::numeric_limits<double>::max_digits10 << std::endl;
return 0;
}
This gives you the maximum digits of precision with your platform/C++ compiler. This shows a maximum of 17 digits of precision with g++ 9.2 on Linux (max_digits10 is C++11 or later, use digits10 with old C++ compilers to show a closely-related metric).
Your desired 42 digits of precision likely far exceed what your modest doubles can handle. There are various special-purpose math libraries that can perform calculations with higher levels of precision, you can investigate those, if you wish.
You did not initialize or assign any value to val, but you are reading it when you get to the first iteration of
val = val + 4*(pow(-1.00,i)/(1 + 2*i));
This cause your program to have undefined behavior. Initialize val, probably to zero:
long double val = 0; // the series output
That aside, as mentioned in the answer of #SamVarshavchik there is a hard limit on the precision you can reach with the built-in floating point types and 42 places significance is almost certainly outside of that. Similarly the integer types that you are using are limited in size to probably at most 2^64 which is approximately 10^19.
Even if these limits weren't the problem, the series requires summation of roughly 10^42 terms to get PI to a precision of 42 places. It would take you longer than the universe has been around to calculate to that precision with all of earths current computing power combined.
How long double fits so many characters in just 12 bytes?
I made an example, a C ++ factorial
when entering a large number, 1754 for example it calculates with a number that apparently would not fit a long double type.
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
unsigned int n;
long double fatorial = 1;
cout << "Enter number: ";
cin >> n;
for(int i = 1; i <=n; ++i)
{
fatorial *= i;
}
string s = to_string(fatorial);
cout << "Factorial of " << n << " = " <<fatorial << " = " << s;
return 0;
}
Important note:
GCC Compiler on Windows, by visual Studio long double behaves like a double
The problem is how is it stored or the to_string function?
std::to_string(factorial) will return a string containing the same result as std::sprintf(buf, "%Lf", value).
In turn, %Lf prints the entire integer part of a long double, a period and 6 decimal digits of the fractional part.
Since factorial is a very large number, you end up with a very long string.
However, note that this has nothing to do with long double. A simpler example with e.g. double is:
#include <iostream>
#include <string>
int main()
{
std::cout << std::to_string(1e300) << '\n';
return 0;
}
This will print:
10000000000000000525047602 [...300 decimal digits...] 540160.000000
The decimal digits are not exactly zero because the number is not exactly 1e300 but the closest to it that can be represented in the floating-point type.
It doesn't fit that many characters. Rather, to_string produces that many characters from the data.
Here is a toy program:
std::string my_to_string( bool b ) {
if (b)
return "This is a string that never ends, it goes on and on my friend, some people started typing it not knowing what it was, and now they still are typing it it just because this is the string that never ends, it goes on and on my friend, some people started typing it not knowing what it was, and now they still are typing it just because...";
else
return "no it isn't, I can see the end right ^ there";
}
bool stores exactly 1 bit of data. But the string it produces from calling my_to_string can be as long as you want.
double's to_string is like that. It generates far more characters than there is "information" in the double.
This is because it is encoded as a base 10 number on output. Inside the double, it is encoded as a combination of an unsigned number, a sign bit, and an exponential part.
The "value" is then roughly "1+number/2^constant", times +/- one for the sign, times "2^exponential part".
There are only a certain number of "bits of precision" in base 2; if you printed it in base 2 (or hex, or any power-of-2 base) the double would have a few non-zero digits, then a pile of 0s afterwards (or, if small, it would have 0.0000...000 then a handful of non-zero digits).
But when converted to base 10 there isn't a pile of zero digits in it.
Take 0b10000000 -- aka 2^8. This is 256 in base 10 -- it has no trailing 0s at all!
This is because floating point numbers only store an approximation of the actual value. If you look at the actual exact value of 1754! you'll see that your result becomes completely different after the first ~18 digits. The digits after that are just the result of writing (a multiple of) a large power of two in decimal.
I am having trouble figuring out how to separate each digit in an integer number. Basically, I have to ask the user what the base number is, and then ask them for two integer numbers. Now, I have the task of checking to make sure each digit in the two integers is smaller than the base number (I have no idea how to do this!).
An example would be something like this:
Enter a base:
3
Enter your first number:
00120
Enter your second number:
11230
I would have to check each digit in the first and second number. Where the first number would be valid because all digits are smaller than 3, and the second number would be invalid because it has a 3 in it which is not smaller than the base.
I've spent multiple hours trying to figure this out on my own and have had no luck.
If you're asking for user input, you don't yet have any integers. You have text, and all you need to do is check whether the text contains valid digit characters. As long as you don't get into bases greater than 10, that's simple, because the characters '0' ..'9' are required to be contiguous and increasing, so you can convert a digit character to its numerical value by subtracting '0' from it.
bool is_valid(char ch, int base) {
return isdigit(ch) && ch - '0' < base;
}
If you are sure that the input does not contain any non-number characters, you can use the % operator to check every digit explicitly. Here is a simple representation of what I mean:
#include <iostream>
bool isValid(int numb, int base) {
do {
if (numb % 10 >= base) { // if the digit cannot be used with this base
return false; // the integer is invalid
}
} while (numb /= 10);
return true; // if all the digits passed the above test,
// the integer is valid
}
int main() {
int numb, base;
std::cin >> numb >> base;
std::cout << "input "
<< (isValid(numb, base) ? "is " : "is not ")
<< "valid " << std::endl;
return 0;
}
Let's say we have hex number
x = 0x345ABC678
how can I get single hex digit (0-15) for given position >>using bitwise operators only<< ?
for example I want to get 4th number (0xA) or 6th (0xC) from hex number.
To make a long story short, I want to brute-force loop thru big database of words I converted them to 64-bit numbers (instead of strings) for example word "PUZZLER" is a number 29996611546. A is 1, Z is 33. So I want to get third letter (stored as decimal 1-33) from int 29996611546. If you could explain to me how to deal with hexadecimals I can use it in my script.
I am simple PHP programmer so I haven't had to use bitwise operators in long long time, I hope you can help me.
Steve Summit's solution/explanation is clear.
Alternatively, a 64bit number can be split into 16 hexa digits using variable bit mask. Then leading zeros can be omitted to display the meaningful digits only.
#include <iostream>
int main()
{
using namespace std;
typedef unsigned long long u64;
u64 number = 0x345ABC678;
int digits[16] = {0};
for( int i = 0; i < 16; i++ ) // fill in all 16 digits, incl. possible leading zero.
{
int shift_bits = 64 - 4 * ( i + 1 );
u64 mask = 0xFULL << shift_bits;
digits[i] = ( number & mask ) >> shift_bits;
}
int j = 0;
while( !digits[j] ){ j++; } // find the first index with non-zero digit.
cout << hex << uppercase;
cout << "digit #4 = " << hex << digits[ j + 3 ] << endl;
cout << "digit #6 = " << hex << digits[ j + 5 ] << endl;
}
Outcome:
digit #4 = A
digit #6 = C
You could start with something like
(x >> ((8 - i) * 4)) & 0xf
This numbers the digits from left to right, 1-8.
To explain how it works: Consider the example 0x45ABC678. Suppose we want the 3rd digit. We want to shift the number to the right using the >> operator, then pick off the last digit. In this case, we want to shift it to the right by 5 hex digits (which is 5*4 = 20 bits), throwing away the BC678 and leaving 0x45A. Then, when we pick off the last digit using a bitwise AND with 0xf, we get the last digit 0xA.
To get the first digit we have to shift by 7 digits. To get the third digit we have to shift by 5 digits. To get the 8th digit we have to shift by 0 digits. 8 - i gives us that pattern.
#include <iostream>
#include <iomanip>
using namespace std;
int a[8], e[8];
void term (int n)
{
a[0]=1;
for (int i=0; i<8; i++)
{
if (i<7)
{
a[i+1]+=(a[i]%n)*100000;
}
/* else
{
a[i+1]+=((a[i]/640)%(n/640))*100000;
}
*/
a[i]=a[i]/(n);
}
}
void sum ()
{
}
int factorial(int x, int result = 1)
{
if (x == 1)
return result;
else return factorial(x - 1, x * result);
}
int main()
{
int n=1;
for (int i=1; i<=30; i++)
{
term(n);
cout << a[0] << " "<< a[1] << " " << a[2] << " "
<< a[3] << " " << a[4] << " " << a[5]<< " "
<< " " << a[6] << " " << a[7] << endl;
n++;
for (int j=1; j<8; j++)
a[j]=0;
}
return 0;
}
That what I have above is the code that I have thus far.
the Sum and the rest are left purposely uncompleted because that is still in the building phase.
Now, I need to make an expansion of euler' number,
This is supposed to make you use series like x[n] in order to divide a result into multiple parts and use functions to calculate the results and such.
According to it,
I need to find the specific part of the Maclaurin's Expansion and calculate it.
So the X in e=1+x+(1/2!)*x and so on is always 1
Giving us e=1+1+1/2!+1/3!+1/n! to calculate
The program should calculate it in order of the N
so If N is 1 it will calculate only the corresponding factorial division part;
meaning that one part of the variable will hold the result of the calculation which will be x=1.00000000~ and the other will hold the actual sum up until now which is e=2.000000~
For N=2
x=1/2!, e=previous e+x
for N=3
x=1/3!, e=previous e+x
The maximum number of N is 29
each time the result is calculated, it needs to hold all the numbers after the dot into separate variables like x[1] x[2] x[3] until all the 30~35 digits of precision are filled with them.
so when printing out, in the case of N=2
x[0].x[1]x[2]x[3]~
should come out as
0.50000000000000000000
where x[0] should hold the value above the dot and x[1~3] would be holding the rest in 5 digits each.
Well yeah Sorry if my explanation sucks but This is what its asking.
All the arrays must be in Int and I cannot use others
And I cant use bigint as it defeats the purpose
The other problem I have is, while doing the operations, it goes well till the 7th.
Starting from the 8th and so on It wont continue without giving me negative numbers.
for N=8
It should be 00002480158730158730158730.
Instead I get 00002 48015 -19220 -41904 30331 53015 -19220
That is obviously due to int's limit and since at that part it does
1936000000%40320
in order to get a[3]'s value which then is 35200 which is then multiplied by 100000
giving us a 3520000000/40320, though the value of a[3] exceeds the limit of integer, any way to fix this?
I cannot use doubles or Bigints for this so if anyone has a workaround for this, it would be appreciated.
You cannot use floating point or bigint, but what about other compiler intrinsic integral types like long long, unsigned long long, etc.? To make it explicit you could use <stdint.h>'s int64_t and uint64_t (or <cstdint>'s std::int64_t and std::uint64_t, though this header is not officially standard yet but is supported on many compilers).
I don't know if this is of any use, but you can find the code I wrote to calculate Euler's number here: http://41j.com/blog/2011/10/program-for-calculating-e/
32bit int limits fact to 11!
so you have to store all the above facts divided by some number
12!/10000
13!/10000
when it does not fit anymore use 10000^2 and so on
when using the division result is just shifted to next four decimals ... (as i assumed was firstly intended)
of course you do not divide 1/n!
on integers that will be zero instead divide 10000
but that limits the n! to only 9999 so if you want more add zeroes everywhere and the result are decimals
also i think there can be some overflow so you should also carry on to upper digits