Wrong Answer for n = 656 Nth Fibonacci Number using Dynamic Programmin - recursion

class Solution {
public:
long long int nthFibonacci(long long int n){
// code here
//TABULATION
long long int lookup[1001];
lookup[0]=0;
lookup[1]=1;
for(long long int i=2;i<=n;i++){
lookup[i]=lookup[i-1]+lookup[i-2];
}
return (lookup[n]%1000000007);
}
};
When I submit it on GFG, it is showing that your code is giving wrong output for n=656
Wrong Answer. !!!Wrong Answer
Possibly your code doesn't work correctly for multiple test-cases (TCs).
The first test case where your code failed:
Input:
656
Its Correct output is:
823693831
And Your Code's output is:
-584713349

Fibonacci numbers grow quite quickly.
fib(n) / (pow(phi, n)) -> 1/sqrt(5) as n -> infinity
where phi is the golden ratio, phi ~= 1.618
This means that fib(n) requires around
n*log2(phi)-0.5log2(5) ~ 0.694*(n-2) bits.
so fib(656) needs about 452 bits.
A long long int is unlikely to be that big!
In your original code the table, of long long ints, cannot hold the correct result for the larger fibonacci numbers.
In C (and I think C++) it is awkward to detect and correct overflow. It is better to ensure that it never happens. In your case you only want the fibonacci numbers mod m (m=1000000007). So you can fill the table with the fibonacci numbers mod m instead. Since m fits in 32 bits, all numbers modulo that and the sum of two of them fit in 32 bits and so overflow cannot occur.
By the way you have some redundant mods in your amended code; you could have
for(long long int i=2;i<=n;i++){
lookup[i]=(lookup[i-1]+lookup[i-2])%mod;
}
bacause when you use it lookup[i-1] has already been reduced mod m.

Update: found the correct solution to the problem but still don't know what was wrong with my earlier code
If someone can have a look at the correct solution and point out my mistake..Thanks in advance!!
Correct Solution:
class Solution {
public:
long long int nthFibonacci(long long int n){
// code here
//TABULATION
const long long int mod=1000000007;
long long int lookup[1001];
lookup[0]=0;
lookup[1]=1;
for(long long int i=2;i<=n;i++){
lookup[i]=(lookup[i-1]%mod+lookup[i-2]%mod)%mod;
}
return lookup[n];
}
};

Related

QT Using calculations for vertices [duplicate]

I'm learning C++, and encountering these problems in a simple program, so please help me out.
This is the code
#include<iostream>
using std::cout;
int main()
{ float pie;
pie = (22/7);
cout<<"The Value of Pi(22/7) is "<< pie<<"\n";
return 0;
}
and the output is
The Value of Pi(22/7) is 3
Why is the value of Pi not in decimal?
That's because you're doing integer division.
What you want is really float division:
#include<iostream>
using std::cout;
int main()
{
float pie;
pie = float(22)/7;// 22/(float(7)) is also equivalent
cout<<"The Value of Pi(22/7) is "<< pie<<"\n";
return 0;
}
However, this type conversion: float(variable) or float(value) isn't type safe.
You could have gotten the value you wanted by ensuring that the values you were computing were floating point to begin with as follows:
22.0/7
OR
22/7.0
OR
22.0/7.0
But, that's generally a hassle and will involve that you keep track of all the types you're working with. Thus, the final and best method involves using static_cast:
static_cast<float>(22)/7
OR
22/static_cast<float>(7)
As for why you should use static_cast - see this:
Why use static_cast<int>(x) instead of (int)x?
pie = (22/7);
Here the division is integer division, because both operands are int.
What you intend to do is floating-point division:
pie = (22.0/7);
Here 22.0 is double, so the division becomes floating-point division (even though 7 is still int).
The rule is that IF both operands are integral type (such as int, long, char etc), then it is integer division, ELSE it is floating-point division (i.e when even if a single operand is float or double).
Use:
pi = 22/7.0
If u give the two operands to the / operator as integer then the division performed will be integer division and a float will not be the result.

Arduino loop update of a variable is incorrect

I've got the following code snippet in the setup() function:
...
unsigned int a0val;
unsigned int a0total = 0;
...
for (i = 0; i < 1000; i++) {
a0val = analogRead(A0);
Serial.println(a0val);
a0total += a0val;
}
Serial.println(a0total);
...
This is done to baseline the analog value at startup to account for different types of sensors being used. One type may read 0 and another may read some non-zero value. The point is to have a starting point reference by averaging 1000 readings at startup time. 1000 is obviously overkill, I'll cut back later.
Now, with 1000 readings somewhere between 128 and 130, I expect a0total to be around 129,000. However, the total consistently comes out less than half that number, like 63,722 in one example. It's not even half, it's less than that.
Another example: I add up the first 500 readings when they are all around 350-352, and the total came out to 43614. It looks like wrap-around, but I'm using unsigned int for both values so that can't be happening.
So to me it almost looks like "a0total += a0val" is not updating every loop, but that doesn't make sense either.
What am I missing?
Thanks,
Ron
You are missing size of unsigned int on this platform. It is 16bits and therefore the maximum value is 65535.

Conversion with Pointsers in C

I need to implement but I am not sure how can I as I am completely new into this. A function called get_values that has the prototype:
void get_values(unsigned int value, unsigned int *p_lsb, unsigned int *p_msb,
unsigned int *p_combined)
The function computes the least significant byte and the most significant byte of the value
parameter. In addition, both values are combined. For this problem:
a. You may not use any loop constructs.
b. You may not use the multiplication operator (* or *=).
c. Your code must work for unsigned integers of any size (4 bytes, 8 bytes, etc.).
d. To combine the values, append the least significant byte to the most significant one.
e. Your implementation should be efficient.
The following driver (and associated output) provides an example of using the function you are
expected to write. Notice that in this example an unsigned int is 4 bytes, but your function
needs to work with an unsigned int of any size.
Driver
int main() {
unsigned int value = 0xabcdfaec, lsb, msb, combined;
get_values(value, &lsb, &msb, &combined);
printf("Value: %x, lsb: %x, msb: %x, combined: %x\n", value, lsb, msb, combined);
return 0;
}
Output
Value: abcdfaec, lsb: ec, msb: ab, combined: abec
I think you want to look into bitwise and and bit shifting operators. The last piece of the puzzle might be the sizeof() operator if the question is asking that the code should work with platforms with different sized int types.

Unexpected integer math results on Arduino

I'm trying to smoothly transition an RGB LED from one colour to another. As part of the logic for this I have the following function to determine how big the change will be (it multiplies by a factor f to avoid floating-point math):
int colorDelta(int from, int to, int f) {
int delta;
if (to == from) {
delta = 0;
} else {
delta = (to - from) * f;
}
return delta;
}
When I call colorDelta(0, 255, 1000) I expect the result to be -255000 but instead the function returns 7144.
I've tried performing the operation as directly as possible for debugging, but Serial.print((0 - 255) * 1000, DEC); also writes 7144 to the serial port.
What have I foolishly overlooked here? I'd really like to see the (smoothly transitioning) light. ;)
I would suspect an integer overflow: the int type being incapable of holding -255000. By language standard, signed integer overflow is undefined behavior, but in practice the major bits of a result are usually just thrown away (warning: this observation is not meant to be used in writing code, because undefined behavior remains undefined; it's just for those cases when you have to reason about the program that is known to be wrong).
A good way to check it quickly is computing a difference between your real result and your expected one: -255000 - 7144 = -262144. The latter is -(1<<18), which is the indication that my suspicions are well-founded.

number squared in programming

I know this is probably a very simple question but how would I do something like
n2 in a programming language?
Is it n * n? Or is there another way?
n * n is the easiest way.
For languages that support the exponentiation operator (** in this example), you can also do n ** 2
Otherwise you could use a Math library to call a function such as pow(n, 2) but that is probably overkill for simply squaring a number.
n * n will almost always work -- the couple cases where it won't work are in prefix languages (Lisp, Scheme, and co.) or postfix languages (Forth, Factor, bc, dc); but obviously then you can just write (* n n) or n n* respectively.
It will also fail when there is an overflow case:
#include <limits.h>
#include <stdio.h>
int main()
{
volatile int x = INT_MAX;
printf("INT_MAX squared: %d\n", x * x);
return 0;
}
I threw the volatile quantifier on there just to point out that this can be compiled with -Wall and not raise any warnings, but on my 32-bit computer this says that INT_MAX squared is 1.
Depending on the language, you might have a power function such as pow(n, 2) in C, or math.pow(n, 2) in Python... Since those power functions cast to floating-point numbers, they are more useful in cases where overflow is possible.
There are many programming languages, each with their own way of expressing math operations.
Some common ones will be:
x*x
pow(x,2)
x^2
x ** 2
square(x)
(* x x)
If you specify a specific language, we can give you more guidance.
If n is an integer :p :
int res=0;
for(int i=0; i<n; i++)
res+=n; //res=n+n+...+n=n*n
For positive integers you may use recursion:
int square(int n){
if (n>1)
return square(n-1)+(n-1)+n;
else
return 1;
}
Calculate using array allocation (extremely sub-optimal):
#include <iostream>
using namespace std;
int heapSquare(int n){
return sizeof(char[n][n]);
}
int main(){
for(int i=1; i<=10; i++)
cout << heapSquare(i) << endl;
return 0;
}
Using bit shift (ancient Egyptian multiplication):
int sqr(int x){
int i=0;
int result = 0;
for (;i<32;i++)
if (x>>i & 0x1)
result+=x << i;
return result;
}
Assembly:
int x = 10;
_asm_ __volatile__("imul %%eax,%%eax"
:"=a"(x)
:"a"(x)
);
printf("x*x=%d\n", x);
Always use the language's multiplication, unless the language has an explicit square function. Specifically avoid using the pow function provided by most math libraries. Multiplication will (except in the most outrageous of circumstances) always be faster, and -- if your platform conforms to the IEEE-754 specification, which most platforms do -- will deliver a correctly-rounded result. In many languages, there is no standard governing the accuracy of the pow function. It will generally give a high-quality result for such a simple case (many library implementations will special-case squaring to save programmers from themselves), but you don't want to depend on this[1].
I see a tremendous amount of C/C++ code where developers have written:
double result = pow(someComplicatedExpression, 2);
presumably to avoid typing that complicated expression twice or because they think it will somehow slow down their code to use a temporary variable. It won't. Compilers are very, very good at optimizing this sort of thing. Instead, write:
const double myTemporaryVariable = someComplicatedExpression;
double result = myTemporaryVariable * myTemporaryVariable;
To sum up: Use multiplication. It will always be at least as fast and at least as accurate as anything else you can do[2].
1) Recent compilers on mainstream platforms can optimize pow(x,2) into x*x when the language semantics allow it. However, not all compilers do this at all optimization settings, which is a recipe for hard to debug rounding errors. Better not to depend on it.
2) For basic types. If you really want to get into it, if multiplication needs to be implemented in software for the type that you are working with, there are ways to make a squaring operation that is faster than multiplication. You will almost never find yourself in a situation where this matters, however.

Resources