FIBOFUN - Fun with Fibonacci Series

no tags 

Fibonacci series is a series in which every element is sum of previous 2 elements.

first 2elements are 0,1 and the series goes like 0,1,1,2,3,5,8,13 ........

 

What if you were given 2 random numbers as the starting of the series and u follow the same rule as the fibonacci rule.

for eg. if you were given 2 and 2 .. the series would become

2 2 4 6 10 16 26 .........

 

Now ur task is Simple ...

You will be given 2 numbers a & b .. the first and second term of the series..

you need to calculate the sum of first n numbers of the series so formed..

Since the numbers can be big you need to print the result mod some number 'M' provided in the input.

Input

first line will have single number 't' - number of test cases.

each test case will have 4 numbers a,b,n & M

a- first number of the series

b- second number of the series

n- calculate the sum till n numbers

M- print the result mod M

Output

single number for each case - sum of n terms mod M

Example

Input:
2
2 2 10 21
1 3 10 21

 Output: 13
4

Explanation - for first case series is 2 2 4 6 10 16 26 42 68 110 .. Sum is 286.. o/p = 286%21 = 13
NOTE -
Number of test cases <=100.
0 <= a,b,m <= 10^8
1 <= n <= 10^8
actually n ranges from 1 to 10^8

hide comments
:D: 2012-08-28 08:29:04

I agree that there are other similar groups of problems, but Fibonacci really been done to death, often in harder variations (just search for Fibonacci). On top of that there's a challenge version:
http://www.spoj.pl/problems/FIBFUNCH/

It stays in tutorial.

Sidharth Gupta: 2012-08-28 08:29:04

This is not a tutorial problem! There are many problems out there which are related to one another or are special case of some other problem..

david_8k: 2012-08-28 08:29:04

@Trichromatic, I think you should move back the problem, this is unfair because you're moving it by your own measures, please, bring it back.

Nnavneetsinha: 2012-08-28 08:29:04

This is definitely not a tutorial problem. please bring it back to the classical section.

[Trichromatic] XilinX: 2012-08-28 08:29:04

This one is the special case of my prob. SPP. Moved to tutorial.

Sachin Railhan: 2012-08-28 08:29:04

What is the answer when m=0?
I think m shouldn't be zero.


-----
m is not 0

Last edit: 2012-05-04 13:19:30
Surya kiran: 2012-08-28 08:29:04

please post a test case

hemezh: 2012-08-28 08:29:04

Got AC. I still don't know why my python code didn't work.

Last edit: 2012-04-12 13:47:37
! include(L.ppt): 2012-08-28 08:29:04

Whoops Got AC....:), njoyed solving this...:)

Last edit: 2012-04-01 14:24:43
Xx100m: 2012-08-28 08:29:04

@ Devil D: Despite multiple submissions (last submission id: 6756464) i am getting WA. Can you please tell me where my code is failing?


Added by:Devil D
Date:2012-03-15
Time limit:1s
Source limit:10000B
Memory limit:1536MB
Cluster: Cube (Intel G860)
Languages:All except: ASM64
Resource:Own