How I do fibonaci sequence under 1000? [closed] - c++

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
#include <iostream>
using namespace std;
void main()
{
int i = 0;
while (i < 1000)
{
int TEMP = i * 2;
cout << i << endl;
TEMP = i;
i = i +1;
// ???
}
return;
}
I'm so confused?? :(

The Fibonacci sequence F is F(n) = F(n - 1) + F(n - 2), F(0) = 0, F(1) = 1.
Here's some psuedo-code:
Start Counter1 at 0
Start Counter2 at 1.
For i = 0 to 1000
New value = Counter1 + Counter2
Print new value
Counter2 = Counter1
Counter1 = New Value
End For
This doesn't print out 0 or 1; it starts at F(2). You can easily fix this by just printing out 0 and 1 first. Also, this code prints the first 1000 numbers. If you change this to: While Counter1 < 1000, you'll stop when you reach or pass 1000.
It's up to you to implement it, and make sure you understand how it works.

First you should check that you understand the definition of the Fibonacci numbers.
By definition, the first two Fibonacci numbers are 0 and 1, and each remaining number is the sum of the previous two. Some sources omit the initial 0, instead beginning the sequence with two 1s.
You need two variables to remember the state, not just one as you were trying to do. And you don't multiply by two, you just add the two variables.
#include <iostream>
using namespace std;
int main()
{
int i = 0;
int j = 1;
while (i < 1000)
{
/* Print a number. */
cout << i << endl;
/* Set j to the sum of i and j, and i to the old value of j. */
int TEMP = j;
j += i;
i = TEMP;
}
return 0;
}

If you would like just a hint, Google "recursion".
If you would like the answer, Google "recursion fibonacci C++", but PLEASE try to work it out with the hint above :) It's worth it.

Related

C++ program to find the largest palindrome which is product of two two digit numbers [closed]

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 8 years ago.
Improve this question
I have seen this, but this is not what I am looking for.
The problem is same that is to find the largest palindrome which is the product of two three digit numbers.
Since my program was not working so I made a little change, instead of finding the largest palindrome which is the product of two three digit numbers I have written the program to find the largest palindrome which is the product of two two digit numbers.
Kindly see the program:
#include <iostream>
using namespace std;
int main() {
int i, j, n, s, m, w;
for (i = 99; i > 9; i--) {
for (j = 99; j > 9; j--)
n = i * j;
s = n;
while (n != 0) {
w = 0;
m = n % 10;
w = w * 10 + m;
n = n / 10;
}
if (s == w)
cout << s << endl;
break;
}
return 0;
}
The problem with this program is that it is neither showing any error nor giving any result.
So kindly help me to find the problem in my program.
Right now you are missing the curly braces for the j-loop. The current code is doing 99! * i.
Then you would have to focus on storing the largest palindrome value instead of just printing all those values to the screen (this is considering your implementation, it is not the most efficient one by any means).
Some modified version of your code:
#include <iostream>
using namespace std;
int main() {
int max_product = 0;
for (int i = 99; i > 9; i--) {
for (int j = i; j > 9; j--) {
int product = i * j;
if (product < max_product)
break;
int number = product;
int reverse = 0;
while (number != 0) {
reverse = reverse * 10 + number % 10;
number /= 10;
}
if (product == reverse && product > max_product) {
max_product = product;
}
}
}
cout << "Solution: " << max_product << endl;
return 0;
}
You have various problems:
Need one more pair of {, }. After the for-loop of j. The only instruction the for-loop of j is executing is: n = i * j; with the braces the rest of the instruction (testing if it's a palindrome) are out of the loop.
the variable w the reverse of the number to test for palindrome is reset his value to 0 in every execution of while (n != 0) loop resulting in incorrect reverse value (and never find the palindrome).
The max palindrome product of 2 two digits number don't have to be the first one found with this 2 for-loop, eg: suppose that there is 2 valid solutions i = 98, j = 2 and i = 70, j = 65 in this case i*j would be in first solution = 196 in the second = 4550 and when you found the first you could not stop the search. In your code using the break don't do what I think you are waiting for (stop the search), only stop the search with the actual i value.
Some notes about the modified code:
The two for-loop don't need to be from 99..9, in this case you are testing a lot of product two times (eg: 98*99, are testing when i == 98 and j == 99 and i == 99 and j == 98), you could restrict j to be always less or equal to i.
Using max_product to maintain the maximum palindrome product found. And use that info in the inner loop (if (product < max_product)) for early exit when no better solution could be found.

Converting integer into array of digits [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I need to convert two integers into two arrays of digits, so for example 544 would become arr[0] = 5, arr[1] = 4, arr[2] = 4.
I have found some algorithms doing this, but they create new array, and return this. I would have to allocate this memory for two arrays, so I wanna pass two integers by reference and do this on them directly.
I guess I can do this, because these integers are in fact template types, so they should be changeable. That's why I added C++ tag here.
Just using something like this:
int n = 544; // your number (this value will Change so you might want a copy)
int i = 0; // the array index
char a[256]; // the array
while (n) { // loop till there's nothing left
a[i++] = n % 10; // assign the last digit
n /= 10; // "right shift" the number
}
Note that this will result in returning the numbers in reverse order. This can easily be changed by modifying the initial value of i as well as the increment/decrement based on how you'd like to determine to length of the value.
(Brett Hale) I hope the poster doesn't mind, but I thought I'd add a code snippet I use for this case, since it's not easy to correctly determine the number of decimal digits prior to conversion:
{
char *df = a, *dr = a + i - 1;
int j = i >> 1;
while (j--)
{
char di = *df, dj = *dr;
*df++ = dj, *dr-- = di; /* (exchange) */
}
}
A simple solution is:
int i = 12312278;
std::vector<int> digits;
while (i)
{
digits.push_back(i % 10);
i /= 10;
}
std::reverse(digits.begin(), digits.end());
or, string based ( i >= 0 )
for (auto x : to_string(i))
digits.push_back(x-'0');
Call the integer a.
To get the units digit of a, a % 10
To shift a down so the tens is the units digit, a / 10
To know when you're done, a == 0
To know how large your array needs to be in the first place, min(ceil(log(a+1, 10)), 1) (to convince yourself this works, try the logarithm part of it in a calculator. if you don't have multiple argument log, use the identity log(x,y) == log(x)/log(y))
You can do something like this if you are using C++:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
int a=544;
stringstream str;
str << a;
string arr;
str>>arr;
for(int i=0; i<arr.length(); i++)
{
cout << arr[i];
}
system("pause");
return 0;
}

For which cases does this algorithm fail? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
What does it do - element at index 'i' is the product of all input elements except for the input element at 'i'.
As an example, if arr = { 1, 2, 3, 4 }, then
output = { 2*3*4, 1*3*4, 1*2*4, 1*2*3 }.
#include<cstdio>
#include<iostream>
using namespace std;
int main(){
int n;
long long int arr[1000]={0},prod=1;
cin>>n;
for(int i=0;i<n;i++){
cin>>arr[i];
prod*=arr[i];
}
if(prod!=0)
for(int i=0;i<n;i++){
cout<<(prod/arr[i])<<endl;
}
else
for(int i=0;i<n;i++){
cout<<"0"<<endl;
}
return 0;
}
The simplest case for which it fails is 2 0 1. The correct result would be 1 0, your result is 0 0.
More generally, it fails if there is exactly one zero and at least one non-zero in the input set.
As was already noted, the problem is when one of the inputs is zero, and you try to divide by zero. To properly compute the products, an algorithm which only performs multiplications and no divisions is needed, such as the following one.
#include <stdio.h>
#include <stddef.h>
// Input: an array of 2^(exp) doubles
// Output: an array of 2^(exp) doubles, where each one is the
// product of all the numbers at different indices in
// the input
// Return value: the product of all inputs
double products (unsigned int exp, const double *in, double *out)
{
if (exp == 0) {
out[0] = 1;
return in[0];
}
size_t half_n = (size_t)1 << (exp - 1);
double prod_left = products(exp - 1, in, out);
double prod_right = products(exp - 1, in + half_n, out + half_n);
for (size_t i = 0; i < half_n; i++) {
out[i] *= prod_right;
out[half_n + i] *= prod_left;
}
return prod_left * prod_right;
}
int main ()
{
double in[8] = {1, 2, 3, 4, 5, 6, 7, 8};
double out[8];
products(3, in, out);
for (size_t i = 0; i < 8; i++) {
printf("%f ", out[i]);
}
printf("\n");
return 0;
}
This requires O(n*log(n)) time and no extra space, except for the O(log(n)) space used by the recursion. While it's nice and easy to understand, it is not optimal; see this question.

Optimization of Algorithm [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
Here is the link to the problem.
The problem asks the number of solutions to the Diophantine equation of the form 1/x + 1/y = 1/z (where z = n!). Rearranging the given equation clearly tells that the answer is the number of factors of z2.
So the problem boils down to finding the number of factors of n!2 (n factorial squared).
My algorithm is as follows
Make a Boolean look up table for all primes <= n using Sieve of Eratosthenes algorithm.
Iterate over all primes P <= n and find its exponent in n!. I did this using step function formula. Let the exponent be K, then the exponent of P in n!2 will be 2K.
Using step 2 calculate number of factors with the standard formula.
For the worst case input of n = 106, my c code gives answer in 0.056s.
I guess the complexity is no way greater than O(n lg n).
But when I submitted the code on the site, I could pass only 3/15 test cases with the verdict on the rest as time limit exceeded.
I need some hints for optimizing this algorithm.
Code so far:
#include <stdio.h>
#include <string.h>
#define ULL unsigned long long int
#define MAXN 1000010
#define MOD 1000007
int isPrime[MAXN];
ULL solve(int N) {
int i, j, f;
ULL res = 1;
memset(isPrime, 1, MAXN * sizeof(int));
isPrime[0] = isPrime[1] = 0;
for (i = 2; i * i <= N; ++i)
if (isPrime[i])
for (j = i * i; j <= N; j += i)
isPrime[j] = 0;
for (i = 2; i <= N; ++i) {
if (isPrime[i]) {
for (j = i, f = 0; j <= N; j *= i)
f += N / j;
f = ((f << 1) + 1) % MOD;
res = (res * f) % MOD;
}
}
return res % MOD;
}
int main() {
int N;
scanf("%d", &N);
printf("%llu\n", solve(N));
return 0;
}
You have an int overflow here:
for (j = i, f = 0; j <= N; j *= i)
If 46340 < i < 65536 and for many larger i, in the second iteration j will be negative if overflow wraps around (it is undefined behaviour, so anything could happen).
Replace it with e.g.
for(j = N / i, f = 0; j > 0; j /= i) {
f += j;
}
It is, however, unlikely that the extra iterations due to the overflow would cause a "time limit exceeded", that will likely only cause wrong results.
So the generic advice is
Sieve only odd numbers, perhaps also eliminate multiples of 3 from the sieve. Eliminating the odd numbers from the sieve roughly halves the time needed to sieve.
Don't use an entire int for the flags, use bits or at least chars. That gives better cache locality and a further speedup.

confused with c++ program? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
I have compiled the following program and i know what it does, it takes ten numbers multiplies it my itself and then at the end add their total together.
#include <iostream>
using namespace std;
main()
{
int a[10];//1
int sumOfSquares = 0 ;//2
int i =0; //3`enter code here`
cout << "Please enter the ten numbers one by one " << endl;//4
for (i = 0 ; i < 10 ; i++)//5 dont get what this does,
// obviously its a for loop,
// but why does it increment i by one
{
cin >> a [i];//6 this means store the 10 numbers
// in array a and refer to it by the variable i
}
for (i = 0 ; i < 10 ; i++) //7 again i dont get why this is here
{
sumOfSquares = sumOfSquares + a[i]*a[i];//8
}
cout << "The sum of squares is "<< sumOfSquares << endl; //9
}
why does it increment i by one
Array indexes run from 0 to N-1, where N is the number of elements in the array.
i++ increments the value of i by 1 (equivalent to i = i + 1;). Incrementing i in the for loop is a construct for accessing each element of the array a (in order):
for (int i = 0; i < 10; i++)
{
a[i] = 2; /* just example */
}
is equivalent to:
a[0] = 2;
a[1] = 2;
...
a[9] = 2;
As others have commented, get a C++ book (see this SO question for a list of C++ books).
#include <iostream>
using namespace std;
main()
{
//declare space in memory for 10 numbers to be stored sequentially
//this is like having ten variables, a1, a2, a3, a4 but rather than having
//hardcoded names, you can say a[4] or rather i=4, a[i], to get variable a4.
int a[10];
int sumOfSquares = 0 ; //space for a number to be stored called sumOfSquares
int i =0; //space for a number to be stored called i
cout << "Please enter the ten numbers one by one " << endl; //print msg to screen
for (i = 0 ; i < 10 ; i++) //make i = 0; while i < 10 run this code! increase i by 1 each time
{
//a stores 10 numbers. put the number the user entered in space
//a[0] the first time, a[1] the second time, a[2] the third time etc etc.
cin >> a [i];
}
//run this code 10 times, with i=0 the first time, i=1 the second time,
// i=3 the third time etc etc.
for (i = 0 ; i < 10 ; i++)
{
//get the number at a[0] multiple it by the number at a[0]
//add it to value already in sumOfSquares so this number goes up and up and up.
//the second time through the loop get a[1] and multiply it by a[1].
sumOfSquares = sumOfSquares + a[i]*a[i];
}
//print answer to screen
cout << "The sum of squares is "<< sumOfSquares << endl; //9
}