Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
How can one calculate nth Fibonacci number in C/C++? The Fibonacci number can contain upto 1000 digits. I can generate numbers upto 2^64 (unsigned long long). Since that is the limit of numbers, so I am guessing there has to be some other way of doing it - which I do not know of.
EDIT:
Also, it has to be done without using any external libraries.
I'll give a few hints since you haven't indicated that you've started yet.
A thousand digits is a lot. More than any built-in numeric type in C or C++ can hold.
One way to get around it is to use an arbitrary-precision math library. This will have constructs that will give you basically as many digits as you want in your numbers.
Another way is to roll your own cache-and-carry:
unsigned short int term1[1024]; // 1024 digits from 0-9
unsigned short int term2[1024]; // and another
unsigned short int sum[1024]; // the sum
addBigNumbers(&term1, &term2, &sum); // exercise for the reader
I'd expect the algorithm for addBigNumbers to go something like this:
Start at the ones digit (index 0)
Add term1[0] and term2[0]
Replace sum[0] with the right digit of term1[0] + term2[0] (which is ... ?)
Keep track of the carry (how?) and use it in the next iteration (how?)
Repeat for each digit
Now, since you're calculating a Fibonacci sequence, you'll be able to re-use these big numbers to get to the next term in the sequence. You might find that it's faster not to copy them around but to just change which ones are the terms and which one is the sum on your repeated calls to addBigNumbers.
You could try using GMP for arbitrarily large integers.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I would like an integer in c++ to count up in binary like:
1, 10, 11, 100, 101, 110, 111
But i want to values to be in base 10 like:
one, ten, eleven, one hundred, one hundred and one, etc.
Basically count up in decimal but look like base 10.
Is there a algorithm to do this.
-Joseph
This is how you should proceed:
use a string for binary values to display it
you should implement a cycle which will end when your number reaches 0 and should write the result of currentValue % 2 to the start of your string then divide your number with 2
you should implement a function which will return the humanely readable number text, you might want to take inspiration from here, but a clue is that the digit number % 3 is relevant. If it is 0, then you will need to write the digit if the digit next to it to the left does not happen to be one, so values between 11-19 are an exception here and don't forget thousand, million, billion, if the modulo is 1, then you will have a special text, like eleven, ... nineteen, twenty, ..., ninety and if modulo is 2, then the text will be the digit + "hundred"
You will basically have a number and will be able to get the binary from it and the textual representation as well.
String is not necessary for the algorithm, one can cout a std::bitset as well.
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 have two numbers N and M.
I efficiently want to calculate how many pairs of a,b are there such that 1<=a<=N and 1<=b<=M and a*b is a perfect square.
I know the obvious N*M algorithm to compute this. But i want something better than that.
Thanks for any help in advance. A pseudo code will be more helpful.
EDIT : I think it can be done in a better time may O(m+n) or something like that but calculating new pairs directly from previous pairs rather than iterating over all a and b.
My approach would be this:
for s is quare and s <= N*M
Do a prime factorization of s.
iterate over the partitions of this prime factorization and check which ones fullfill your requirement
Iterating over the possible partitions may be a bit tricky, but I'm quite certain that this is the most efficient approach that is possible.
Iterating over square numbers, on the other hand, is trivial:
for(int i = 0, square = 0; /*whatever*/; square += 2*i++ + 1)
I would go for a way using prime decompositions.
Get a hold of all the prime numbers between 1 and max(N,M), and let us call them the (p0, p1, ... pn)
Then any number a <= N and b <= M can be written as and , for i from 1 to n, where the ai and bi can be any positive integer or 0.
Then, any product a*b can be written as , and the caracterization of a perfect square in that writing would be that all the (ai+bi) need to be even (0 is even, for the record).
Then you somehow need to iterate over all the (ai) such that a <= N, and for each set of (ai) generate all the (bi) such that b <= M and all the (ai+bi) are even.
Not sure that's the anywhere near efficient, but should work just fine.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions must demonstrate a minimal understanding of the problem being solved. Tell us what you've tried to do, why it didn't work, and how it should work. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
This is what I tried:
int i=-1,size=1;
while (i>>1)
size++;
printf("%d",size);
The goal is to determine the size of int without using the sizeof operator.
The above loop turns out to be infinite. Is there a way to fix it so it does what it is intended to do?
Just use unsigned for i, rather than int. They are
guaranteed to have the same size, and right shift of a signed integer is implementation defined (but will usually shift in the sign bit). And don't forget to divide
the results by CHAR_BIT (which is not guaranteed to be 8).
You have chosen a negative number for right-shifting.
Right shifting a negative number, it gets filled with the sign bit 1 (or not, depending on implementation), so your value can never be 0 (=false), which means you get precisely the infinite loop you are complaining about.
your loop is indeed infinite.
start from i = 1 and shift it left till you reach i =0 and stop. you have the bits.
-edit---
this will work for signed as well as unsigned integer alike.
The following lines are part from my really "useless" C++ program... which is calculating powers of 2 only up to 2^63 instead of 2^128 "which is being asked" due to the length of the "unsigned long long" variable which is proposed for numbers with 15 digits accuracy...!!!
Just that....I need a 16 bytes or more variable...which is not provided by:
-__int128(Visual Studio 2010 turns the letters to blue but a red line and a error in debug: "keyword not supported on this architecture"32-bit system)
-Boost::Projects...after I googled it due to the fact that I am a newcomer "I was lost in the universe" when I came across with professionals sites (does boost::bigint...exist??? not a rhetorical question)
(-Multi-typing long of' course)
int main()
{
unsigned long long result;
int i;
const int max=128;
for(i=0, result=1ll; i <= max; ++i,result *=2 )
cout<<setw(3)<< i <<setw(32)<< result <<endl;
system("pause");
return 0;
}
You could find a "bigint" implementation in C++ that implements operator<<() to output to ostream's, but if all you want to do is print out powers of 2 to a console or text string, and you don't need to actually do "bigint" math (except to compute those powers-of-2), there's a simpler approach that will give you powers of 2 out to pretty much as large as you want to go & have the patience to look through:
Store each decimal digit (numbers 0 through 9) as a separate entity, perhaps as an array of chars or ints or in a std::list of the digits. Using a std::list has the advantage that you can easily add new digit places at the front as your number gets bigger, but you can do that almost as easily by storing the digits in reverse order in a std::vector (of course to print them, you have to iterate from the back to the front to print the digits in their proper order).
Once you figure out how you want to store the digits, your algorithm for doubling the number is as follows: Iterate over the digits of the large number, doubling each (mod 10 of course) and carrying any overflow (i.e. a bool that says if its result... before the %10... was greater than 9) from that digit to the next. On the next digit, double it first and then add 1 if the previous digit overflowed. And if that result overflows, carry that overflow on to the next digit & continue to the end of all of the digits. At the end of the digits, if doubling the last digit & adding any overflow from the previous digit caused an overflow in that last digit, then add a new digit & set it to 1. Then print the resulting list of digits.
With this algorithm, you can print powers-of-2 as large as you like. Of course they're not "numbers" in the sense that you can't use them directly in C++ math ops.
SSE and AVX intrinsics go up to 256 bytes, given a modern CPU. They're named __m128i and __m256i.
128 bit integer is a really big integer. You should implement your own data type. You can create an array of shorts, store there numbers (digits) and implement multiplying, just like you do in your math notebook, that's probably the simplest approach.
This one is not finished, of course! The '2' is still missing ;)
i am trying to figure out how to handle overflow for addition, subtraction, multiplication and division, for two very large integer numbers. Any feedback/input would be appreciated. Does anyone know any algorithms for this and/or sources I could consult?
(I have done research before posting and am just not sure how to tackle this and)
EDIT: for two very large integer numbers
This seems to be similar to the questions
Check for overflow condition in an arithmetic operation
and
How to detect integer overflow?
Because an integer divided by an integer is rarely an integer, this is impossible in general.
That said, this is what I think you want:
http://gmplib.org/
It handles integers and rationals of arbitrary size.
If you want to avoid the condition of overflow occurring, one way would be to use a linked list to store parts of a number and then perform calculations on the parts individually, and add more nodes to the list to handle the excess digits when needed.
Example
1234567890 can be stored as -> 12,34,56,78,90
To multiply, each unit will be multiplied and carry taken over to next unit -> 1,23,45,67,89,0
Keep in mind though, that it is easier to divide it into single digit units, like 1,2,3,4,5 rather than 1,23,45 as this makes the operations simpler.
EDIT :: The word "handle" is not the word you should be using
If you wonder how you can check overflows, I would recommend this:
log(a) + log(b) = log(a*b)
Correct => no overflow
Not correct => overflow
(... and now fingers crossed that nobody finds a contra-example and please, don't start about negative numbers, this is a uint approach).