To calculate every third term in a Fibonacci sequence - fibonacci

int Fib1, Fib2, Fib3, FibSum;
Fib1 = 0;
Fib2 = 1;
while(Fib3 < 500000)
{
Fib3 = Fib1 + Fib2;
Fib1 = Fib2;
Fib2 = Fib3;
FibSum = Fib3 + Fib1;
}
printf("%d\n", FibSum);
return 0;
I want to sum every third term of a fibonacci series but my answers is 832040 and it must be 158905...any help will be grateful!

This seems like homework but hey, I was once a student too. Still learning.
I wrote the following code in R but you can follow along enough:
fib1 <- 0
fib2 <- 1
fib3 <- 0
fib_sum <- 0
placeholder <- 0
while(fib3 < 500000)
{
placeholder <- placeholder + 1
f1 <- fib1
f2 <- fib2
f3 <- fib3
fib3 <- fib1 + fib2
fib1 <- fib2
fib2 <- fib3
if(placeholder %% 3 == 0)
{
fib_sum <- fib_sum + f1
print(paste('postsum [placeholder, fib_sum, fib1, fib2, fib3]: ',
placeholder, ' ', fib_sum, ' ', f1, ' ', f2, ' ', f3))
}
}
print(fib_sum)
Which results in what you were looking for. Lesson time, since this seems to be homework help. To help you out on the path of being a better programmer I would suggest taking the approach of scaffolding (just simply printing out everything after each line or so) when doing programming.
This will help you to see how you program is evolving as you do it.
Is there a better solution to the one below? I am sure there is but since I output the code as I was programming, I was able to come to the conclusion a lot quicker.
Hope that helps.

There is a shortcut to calculate every third fibonacci number:
If you want to sum up 1,5,21,89,377 ...then you sum up the first two numbers you have (fibsum = 1 + 5) and calculate and add the next numbers as follows in a loop.
fib1 = 1
fib2 = 5
fib3 = 0
fibsum = fib1 + fib2
while fib3 < 500000 :
fib3 = fib2*4+fib1
if fib3 < 500000:
fibsum += fib3
fib1 = fib2
fib2 = fib3
print fibsum

Here is some working code applying a formula found at HERE
double phi1 = (1 + sqrt(5)) / 2.0;
double phi2 = (1 - sqrt(5)) / 2.0;
int counter = 2;//Third term
int total = 0, term;
while (true) {
term = (pow(phi1, counter) - pow(phi2, counter)) / (phi1 - phi2);
if (term >= 500000)
break;
total += term;
counter += 3;
}
printf("%d\n", total);
return 0;
EDIT: Just realized this was posted OVER A YEAR AGO

Related

Unable to understand firstTerm = secondTerm; secondTerm = nextTerm; in fibonacci series

class Main {
public static void main(String[] args) {
int n = 5, firstTerm = 0, secondTerm = 1;
System.out.println("Fibonacci Series till " + n + " terms:");
for (int i = 1; i <= n; ++i) {
System.out.print(firstTerm + " ");
// compute the next term
int nextTerm = firstTerm + secondTerm;
firstTerm = secondTerm;
secondTerm = nextTerm;
}
}
}
//Q) Unable to understand why firstTerm = secondTerm;
secondTerm = nextTerm; statement is written, can anyone explain me this concept
The fibonnaci sequence is defined by
F(0) = 0 // This is our first term
F(1) = 1 // This is the second term
F(n) = F(n - 1) + F(n - 2)
To calculate a term that is neither the first term, nor the second term, we need to sum, the two previous terms.
This is the reason why while iterating, the second term value is assigned to the first term and so on
You will have more details here

Lua get day of year

I am trying to write a script that determines stardate using the formula
a = LastLeapYearShort (if year is leap year make 4 years ago)
b = 366 + (365 * ((CurrentYearShort - 1) - LastLeapYearShort)
c = DayOfYear - DayOfMonth
d = DayOfMonth
e = (SecondOfMinute + (MinuteOfHour * 60))/1440
f = 36525
st = ((a + b + c + d + e)/f)*100000
separate x.y into x and y
if the century is greater than 19 add 1- to the beginning of x and get the first to digits of y
date = x.y
however I can't seem to determine a way to get DayOfYear. The Current Script I have is
function isLeapYear(year)
return year%4==0 and (year%100~=0 or year%400==0)
end
function lastLeapYear(year)
if(isLeapYear(year))
result = strsub(year,2,4) - 4
else
year = year - 1
if(isLeapYear(year))
result = strsub(year,2,4)
else
year = year - 1
if(isLeapYear(year))
result = strsub(year,2,4)
else
year = year - 1
if(isLeapYear(year))
result = strsub(year,2,4)
else
result = "Invalid"
end
end
end
end
return result
end
function stardate()
yearf = os.date("%Y")
yearh = os.date("%y")
a = lastLeapYear(yearf)
b = (366 + (365 * (yearh - a)))
c = (!!DayOfYear!! - os.date("%d"))
d = os.date("%d")
e = (os.date("%S") + (os.date("%M") * 60))/1440
f = 36525
st = ((a + b + c + d + e)/f)*100000
!!Separate st into x and y!!
if(strsub(yearf,0,2) > 19)
diff = strsub(yearf,0,2) - 19
lead = diff "-" lead
end
return lead.dec
end
if there are any other errors in my code please point them out as I have very little Lua experience.
The day of year is the value of os.date("*t").yday or os.date("%j").
The first expression gives you a number; the second one gives you a string (which can be converted explicitly to a number with tonumber or implicitly when used in an arithmetic operation).
For any one who can't find the proper format string a more advanced list than that on http://www.lua.org/pil/22.1.html (which is where I was looking) can be found on http://docs.rainmeter.net/manual/measures/time

Runtime of while loop pseudocode

I have a pseudocode which I'm trying to make a detailed analysis, analyze runtime, and asymptotic analysis:
sum = 0
i = 1
while (i ≤ n){
sum = sum + i
i = 2i
}
return sum
My assignment requires that I write the cost/runtime for every line, add these together, and find a Big-Oh notation for the runtime. My analysis looks like this for the moment:
sum = 0 1
long i = 1 1
while (i ≤ n){ log n + 1
sum = sum + i n log n
i = 2i n log n
}
return sum 1
=> 2 n log n + log n + 4 O(n log n)
is this correct ? Also: should I use n^2 on the while loop instead ?
Because of integer arithmetic, the runtime is
O(floor(ln(n))+1) = O(ln(n)).
Let's step through your pseudocode. Consider the case that n = 5.
iteration# i ln(i) n
-------------------------
1 1 0 5
2 2 1 5
3 4 2 5
By inspection we see that
iteration# = ln(i)+1
So in summary:
sum = 0 // O(1)
i = 1 // O(1)
while (i ≤ n) { // O(floor(ln(n))+1)
sum = sum + i // 1 flop + 1 mem op = O(1)
i = 2i // 1 flop + 1 mem op = O(1)
}
return sum // 1 mem op = O(1)

Using F# Indexed Properties in a Type

I'm trying to convert the following C# into F#:
public class Matrix
{
double[,] matrix;
public int Cols
{
get
{
return this.matrix.GetUpperBound(1) + 1;
}
}
public int Rows
{
get
{
return this.matrix.GetUpperBound(0) + 1;
}
}
public Matrix(double[,] sourceMatrix)
{
this.matrix = new double[sourceMatrix.GetUpperBound(0) + 1, sourceMatrix.GetUpperBound(1) + 1];
for (int r = 0; r < this.Rows; r++)
{
for (int c = 0; c < this.Cols; c++)
{
this[r, c] = sourceMatrix[r, c];
}
}
}
public double this[int row, int col]
{
get
{
return this.matrix[row, col];
}
set
{
this.matrix[row, col] = value;
}
}
}
This is what I have so far:
type Matrix(sourceMatrix:double[,]) =
let mutable (matrix:double[,]) = Array2D.create (sourceMatrix.GetUpperBound(0) + 1) (sourceMatrix.GetUpperBound(1) + 1) 0.0
member this.Item
with get(x, y) = matrix.[(x, y)]
and set(x, y) value = matrix.[(x, y)] <- value
do
for i = 0 to matrix.[i].Length - 1 do
for j = (i + 1) to matrix.[j].Length - 1 do
this.[i].[j] = matrix.[i].[j]
My type above seems to have two problems I'm not sure how to resolve. The first one is that matrix.[(x, y)] is expected to have type `a[] but has type double[,]. The second is type definitions must have let/do bindings preceding member and interface definitions. The problem with that is I'm trying to populate an indexed property in the do block, which means I have to create it first.
Thanks in advance,
Bob
Regarding your first problem, you want to use matrix.[x,y] instead of matrix.[(x,y)] - your matrix is indexed by two integers, not by a tuple of integers (although these are conceptually similar).
Here's something roughly equivalent to your C#:
type Matrix(sourceMatrix:double[,]) =
let rows = sourceMatrix.GetUpperBound(0) + 1
let cols = sourceMatrix.GetUpperBound(1) + 1
let matrix = Array2D.zeroCreate<double> rows cols
do
for i in 0 .. rows - 1 do
for j in 0 .. cols - 1 do
matrix.[i,j] <- sourceMatrix.[i,j]
member this.Rows = rows
member this.Cols = cols
member this.Item
with get(x, y) = matrix.[x, y]
and set(x, y) value = matrix.[x, y] <- value
This assumes that your matrix can't actually be reassigned (e.g. in the C# you've posted, you could have made your matrix field readonly - unless there's additional code that you've hidden). Therefore, the number of rows and columns can be calculated once in the constructor since the entries of the matrix may change but its size won't.
However, if you want a more literal translation of your code, you can give your newly constructed instance a name (this in this case):
type Matrix(sourceMatrix:double[,]) as this =
let mutable matrix = Array2D.zeroCreate<double> (sourceMatrix.GetUpperBound(0) + 1) (sourceMatrix.GetUpperBound(1) + 1)
do
for i in 0 .. this.Rows - 1 do
for j in 0 .. this.Cols - 1 do
this.[i,j] <- sourceMatrix.[i,j]
member this.Rows = matrix.GetUpperBound(0) + 1
member this.Cols = matrix.GetUpperBound(1) + 1
member this.Item
with get(x, y) = matrix.[x, y]
and set(x, y) value = matrix.[x, y] <- value
type Matrix(sourceMatrix:double[,]) =
let matrix = Array2D.copy sourceMatrix
member this.Item
with get(x, y) = matrix.[x, y]
and set(x, y) value = matrix.[x, y] <- value

How can I do mod without a mod operator?

This scripting language doesn't have a % or Mod(). I do have a Fix() that chops off the decimal part of a number. I only need positive results, so don't get too robust.
Will
// mod = a % b
c = Fix(a / b)
mod = a - b * c
do? I'm assuming you can at least divide here. All bets are off on negative numbers.
a mod n = a - (n * Fix(a/n))
For posterity, BrightScript now has a modulo operator, it looks like this:
c = a mod b
If someone arrives later, here are some more actual algorithms (with errors...read carefully)
https://eprint.iacr.org/2014/755.pdf
There are actually two main kind of reduction formulae: Barett and Montgomery. The paper from eprint repeat both in different versions (algorithms 1-3) and give an "improved" version in algorithm 4.
Overview
I give now an overview of the 4. algorithm:
1.) Compute "A*B" and Store the whole product in "C" that C and the modulus $p$ is the input for that algorithm.
2.) Compute the bit-length of $p$, say: the function "Width(p)" returns exactly that value.
3.) Split the input $C$ into N "blocks" of size "Width(p)" and store each in G. Start in G[0] = lsb(p) and end in G[N-1] = msb(p). (The description is really faulty of the paper)
4.) Start the while loop:
Set N=N-1 (to reach the last element)
precompute $b:=2^{Width(p)} \bmod p$
while N>0 do:
T = G[N]
for(i=0; i<Width(p); i++) do: //Note: that counter doesn't matter, it limits the loop)
T = T << 1 //leftshift by 1 bit
while is_set( bit( T, Width(p) ) ) do // (N+1)-th bit of T is 1
unset( bit( T, Width(p) ) ) // unset the (N+1)-th bit of T (==0)
T += b
endwhile
endfor
G[N-1] += T
while is_set( bit( G[N-1], Width(p) ) ) do
unset( bit( G[N-1], Width(p) ) )
G[N-1] += b
endwhile
N -= 1
endwhile
That does alot. Not we only need to recursivly reduce G[0]:
while G[0] > p do
G[0] -= p
endwhile
return G[0]// = C mod p
The other three algorithms are well defined, but this lacks some information or present it really wrong. But it works for any size ;)
What language is it?
A basic algorithm might be:
hold the modulo in a variable (modulo);
hold the target number in a variable (target);
initialize modulus variable;
while (target > 0) {
if (target > modulo) {
target -= modulo;
}
else if(target < modulo) {
modulus = target;
break;
}
}
This may not work for you performance-wise, but:
while (num >= mod_limit)
num = num - mod_limit
In javascript:
function modulo(num1, num2) {
if (num2 === 0 || isNaN(num1) || isNaN(num2)) {
return NaN;
}
if (num1 === 0) {
return 0;
}
var remainderIsPositive = num1 >= 0;
num1 = Math.abs(num1);
num2 = Math.abs(num2);
while (num1 >= num2) {
num1 -= num2
}
return remainderIsPositive ? num1 : 0 - num1;
}

Resources