General Fibonacci, why is it overflowing? - c

I am trying to create a general fibonacci series where the starting values can be variable, depending on what the user wants. For example, instead of starting with values 0, 1, or 1, 1, as it usually does, it can start with 3, 6, or 10, 21, or whatever the user wants. We then want to get the nth value of that series.
I tried my code for a = 10 and b = 21, and I wanted a big value, however it didn't work. So I started checking where the problem was. With those starting values: for n = 37, 38, 39, the output should be 405812042, 656617677, 1062429719 respectively. When I run my code for values n = 37 and n = 38, both answers are correct. However when I try 39, this is the value I get: 62429712.
This is my code:
#include <stdio.h>
int main(void)
{
unsigned long long a, b, hn, value;
int scenarios;
scanf("%d", &scenarios);
for (int i = 0; i < scenarios; i++){
scanf("%lld%lld%lld", &a, &b, &hn);
if (hn == 1)
value = a;
else if (hn == 2)
value = b;
else{
for (int j = 3; j <= hn; j++){
value = a + b;
a = b;
b = value;
}
//value %= 1000000007;
}
printf("%lld\n", value);
}
}
EDIT: According to the problem specification, the answer should be module 1000000007. The output I get if I get the 514th value is 2903631044495864380, and to be honest I don't know how to verify this value. If I do 2903631044495864380 mod 1000000007, my answer is 170447212, but according to the problem this answer should be 859861000. Any idea how to verify this?

Change this:
scanf("%lld%lld%lld", &a, &b, &hn);
to this:
scanf("%llu%llu%llu", &a, &b, &hn);
Change this:
printf("%lld\n", value);
to this:
printf("%llu\n", value);
since these variables are of type unsigned long long.
EDIT
It seems like (from your edit) you need to change this:
value = a + b;
to this:
value = (a + b) % 1000000007;

You misinterpreted the point where you should calculate the modulo according to your exercise.
You don't compute the end sum before doing modulo, but you apply modulo to the intermediate results:
for (int j = 3; j <= hn; j++)
{
value = (a + b) % 1000000007; // there
a = b;
b = value;
}
Also, change your scan/print format to '%llu', as #gsamaras suggested.

Related

Need help creating function to double the digits of an integer individually

So I'm trying to make a recursive function that takes an integer, let's say 123, and gives back double every single digit in the integer. So 123 would become 248, not 246. The main difference obviously is that instead of doing 123x2, you do (100x2)+(20x2)+(3x2). There is also the condition that if any of the numbers are equal to or greater than 5, you replace it with a 9, so 345 becomes 689. I am trying to create it iteratively before making it recursively and I am running into an issue with the conditions. Heres what I have so far:
int double_digit(int g) {
int dubl = 0;
int mod = 10;
int i = 1;
while (g > 0) {
mod = pow(10, i);
if (g % 10 < 5) {
dubl = dubl + g % mod * 2;
g = g - (g % mod);
i++;
}
else {
dubl = dubl + (9 * (mod / 10));
g = g - (g % mod);
i++;
}
}
printf("%d", dubl);
}
If you run the code, you will see that it works for numbers under 5, but not greater than or equal to, how can I fix it?
WAY too complicated... A lookup table will shrink the code down to almost nothing. This even tries to protect against receiving a negative number.
int double_digit(int g) {
int dd = 0;
for( int w = abs(g), pow = 1; w; w /= 10, pow *= 10 )
dd += pow * "\0\02\04\06\10\011\011\011\011\011"[ w % 10 ];
return g < 0 ? 0 - dd : dd;
}
int main() {
int tests[] = { 42, 256, 123, 578, -3256, };
for( int i = 0; i < sizeof tests/sizeof tests[0]; i++ )
printf( "%d = %d\n", tests[i], double_digit( tests[i] ) );
return 0;
}
42 = 84
256 = 499
123 = 246
578 = 999
-3256 = -6499
EDIT:
C's understanding of octal bytes specified in a character array (aka string) may be new.
Here is an abridged alternative that may not be as confrontational:
int lut[] = { 0, 2, 4, 6, 8, 9, 9, 9, 9, 9, };
for( int w = abs(g), pow = 1; w; w /= 10, pow *= 10 )
dd += pow * lut[ w % 10 ];
And, then there are branchless techniques (overkill in this instance, but useful to consider in other applications):
for( int d, w = abs(g), pow = 1; w; w /= 10, pow *= 10 )
d = (w%10)<<1, dd += pow * (d*(d<9)+(d>8)*9);
In other words, there are lots of ways to achieve objectives. A good exercise is to try to discover those different ways and then to consider where each may be used to the most benefit (and where other methods may not appropriate or as clear.) Write clean, clear, concise code to the best of your abilities.
I've written the recursive version. Without accounting for negative values, the recursive version requires, to the best of my abilities, more code and takes a 'linear' (iterative) problem into other dimensions. Make the method fit the problem, not vice versa.

Convert index to sequence from custom alphabet

I would like to produce a function which takes an integer x and char array in, and returns a string x steps into the sequence.
For example, consider the alphabet 'abc', which would produce the strings a, b, c, aa, ab, ac, ba, bb, bc, ca, cb, cc, aaa, aab... If the index 0 was passed in, I would expect the output to be 'a'; likewise, if the index 34 was passed in, I would expect the output 'cbb'.
For the alphabet '0123456789' I would expect the strings 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 00, 01, 02, 03, 04, 05, 06, 07, 08, 09, 10, 11...
I have written the following thus far, but am getting stuck on cases 21-23, 33-35, 45-47 where the behaviour deviates and I've been staring at this for a number of hours now without a pattern jumping out at me (with respect to the alphabet size and index). At first I didn't notice the issue, using a larger sized alphabet until it created bigger issues further in my program.
I'm not going to pretend the code below is in anyway elegant, following good practice, nor optimised - at this stage I really just want to understand the correct implementation of this pattern and have been changing things all over the place to attempt to resolve the issue. Apologies in advance if the variable names are confusing. Also, is this a common pattern/issue? I have tried to search for similar algorithms but have been unable to find anything with the terms that come to mind.
unsigned long power(int num, int exp)
{
int i;
unsigned long ret = num;
if (exp == 0) return 1;
for (i = 1; i < exp; i++)
{
ret *= num;
}
return ret;
}
unsigned long sumsqr(int base, int exp)
{
unsigned long sum;
for (sum = 0; exp > 0; exp--)
{
sum += power(base, exp);
}
return sum;
}
char * generateStringT(unsigned long index, char * charmap)
{
unsigned long scaler;
unsigned long remainder;
unsigned long divisor;
int base;
int exponent;
int factor;
char * buffer;
char * string;
int i;
buffer = malloc(sizeof(char) * 100);
i = 0;
base = strlen(charmap);
exponent = 0;
divisor = 0;
remainder = index;
while(sumsqr(base, exponent) <= index)
{
exponent++;
}
exponent--;
factor = exponent;
while(factor >= 0)
{
divisor = power(base, factor);
if ((factor > 1) && (exponent > 0))
divisor += power(base, factor-1);
scaler = remainder/divisor;
remainder = remainder - scaler * divisor;
printf("%lu,", scaler);
if ((factor == exponent) && (exponent > 0)) scaler--;
buffer[i++] = charmap[scaler];
factor--;
}
buffer[i++] = '\0';
string = malloc((strlen(buffer) + 1) * sizeof(char));
strcpy(string, buffer);
free(buffer);
return string;
}
What you are trying to do there looks like a base conversion, but actually is slightly different. Any number in any base can be thought as if they have infinitely many preceding zeros (or whatever the least significant digit is at that base) behind the represented number. This is not true in your case.
In your case, you lay importance to the amount of digits on the number you represent, making it slightly more complicated to index them. With bases in maths, it is easy to calculate the index of a represented number in any base b; that is, sum of the rank times the base raised to the power of order for each digit. In your case, the index builds up an additional sum_{k = 1}^{amount.of.digits.on.our.number - 1} base^k. If we subtract that addition from the index, our task becomes rather easy.
That addition can be calculated using your sumsqr function.
Here, I have changed your code just a little, with comments at where I've done changes, which is able to resolve many, just like you expect it to:
// added this
remainder -= sumsqr(base, exponent);
while (factor >= 0)
{
divisor = power(base, factor);
// commented this out
// if ((factor > 1) && (exponent > 0))
// divisor += power(base, factor - 1);
scaler = remainder/divisor;
remainder = remainder - scaler * divisor;
printf("%lu,", scaler);
// commented this out
// if ((factor == exponent) && (exponent > 0))
// scaler--;
buffer[i++] = charmap[scaler];
factor--;
}
I am not exactly sure what you were trying to do with the parts I've commented out. My guess is that you were trying to increase the divisor by that amount of difference I've talked previously, instead of decreasing the index or remainder by that amount.
Hope this helps in any way.
Not a fix (at a glance, your code uses a similar idea -- but more complicated!), but this is the code I used to convert an integer index to an a,b,c-format page number:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char *number_alpha (char *dest, int value, char *base)
{
char *ddest = dest, *startdest = dest, swop;
if (value < 0)
{
value = -value;
*dest = '-';
startdest++;
ddest++;
}
value++;
do
{
*ddest = base[((value-1) % strlen(base))];
ddest++;
value = (value-1)/strlen(base);
} while (value > 0);
*ddest = 0;
ddest--;
while (ddest > startdest)
{
swop = *ddest;
*ddest = *startdest;
*startdest = swop;
startdest++;
ddest--;
}
return dest;
}
int main (int argc, char **argv)
{
int number;
char result[256];
if (argc != 3)
{
printf ("usage: [number] [string]\n");
return -1;
}
number = strtol (argv[1], NULL, 10);
number_alpha (result, number, argv[2]);
printf ("%d in 'base' %s yields %s\n", number, argv[2], result);
return 0;
}
It is very similar to the common task 'convert an integer to decimal notation'. By removing the value++ and changing (value-1) twice to just value in number_alpha, you get a bog-standard Int-To-Ascii routine. This one is special because the "wrap" occurs at a different place: for a base of 0123456789, incrementing 9 shows 00, not 10.
Sample outputs:
0 in 'base' abc yields a
34 in 'base' abc yields cbb
34 in 'base' 0123456789 yields 24
-34 in 'base' abc yields -cbb
9 in 'base' 0123456789 yields 9
10 in 'base' 0123456789 yields 00
--
See Translate a column index into an Excel Column Name for a couple of implementations in other languages. They seem to focus on recursive solutions, where mine is linear (for better or worse).

Finding which Pythagorean triple has the smallest angle

Information: a being the length of the shortest leg of a right triangle and b being the length of the other leg, the larger the difference between a and b the smaller the angle. That is:
the triple (3, 4, 5) has a difference of 4-3=1
the triple (5, 12, 13) has a difference of 12-5=7
Therefore the smallest angle would be in the triple (5, 12, 13)
I'm writing a program that compares all of the pythagorean triples defined in a range and prints the triple with the smallest angle. What I have so far is not working and I have no idea where I can go from here.
#include <stdio.h>
int smallest(int a, int b) {
int difference = b - a;
return 0;
}
int main() {
int a = 0, b = 0, c = 0, n, counter = 1, i = 0;
printf("Please Enter a Positive Integer: \n");
scanf("%d", &n);
for (c = 0; c < n; c++) {
for (b = 0; b < c; b++) {
for (a = 0; a < b; a++) {
if (a * a + b * b == c * c ) {
printf("%d:\t%d %d %d\n", counter++, a, b, c);
}
}
}
i = counter - 1;
}
printf ("The difference is %d\n", smallest(a, b));
printf ("There are %d Pythagorean Triples in this range.\n", i);
return 0;
}
The program just prints the difference is 0
what I am looking for the program to print is, for the example above "The triangle with the smallest angle is (5, 12, 13)"
I know I have to sort the differences and compare them but this is all I have so far, any tips?
Are you sure your 'information' is right? Because triple (30, 40, 50) has a difference of 10 and just the same angle as (3, 4, 5).
You don't have to sort, you have to remember difference/angle/whatever you minimize, as already mentioned in comments. Also, you have to remember values of 'minimal' (a,b,c) to print them later. Something like this:
//...
if (a * a + b * b == c * c ) {
printf("%d:\t%d %d %d\n", counter++, a, b, c); //if you use ++counter instead, you won't need i ;)
if(minDifference < b-a){ //Don't be afraid of variables with long names
minA = a; minB = b; minC = c; minDifference = b-a;
}
}
//...
printf("The triangle with the smallest difference is (%d, %d, %d)", minA, minB, minC);
Your smallest-code returns 0 in every case. Are you sure you don't want to return difference instead (or even b-a)?
int smallest(int a, int b) {
return b-a;
}

Find the sum of all the even-valued terms in the sequence which do not exceed four million

Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
I made the program but my answer doesnt match.
#include<stdio.h>
int main()
{
long unsigned int i,sum=0,x=1,y=2,num;
for(i=0;i<4000000;i++)
{
num=x+y;
if(i%2==0)
sum+=num;
x=y;
y=num;
}
printf("%lu\n",sum);
getchar();
return 0;
}
Three problems I can see:
You should start with x = 1, y = 1, since otherwise you skip the first even-valued Fibonacci;
Your loop condition should be (x + y) <= 4000000
You should test num for even-ness, not i.
(After these changes, it should be obvious that you can omit i entirely, and therefore replace the for loop with a while loop)
In your code you find the sum of fibonacci numbers with even index, not even numbers themselves + you search the first 4000000 numbers in sequence, not the numbers with values <= 4000000. Your code should be something like
while ( y < 4000000){
...
if (y %2 == 0)
sum += y;
}
I've made a minimal set of corrections and now get the right answer. You may learn more by reading this (after all, it was yours, to start with) than by me rambling on about it...
#include <stdio.h>
#define LIMIT (4 * 1000 * 1000)
int main() {
long unsigned int sum = 0, x = 1, y = 2, num;
while (x <= LIMIT) {
if ((x & 1) == 0 && x <= LIMIT)
sum += x;
num = x + y;
x = y;
y = num;
}
printf("%lu\n", sum);
return 0;
}
I think the following line
if(i%2==0)
might instead be
if( num % 2 == 0)
On further thinking, I think you don't actually need the variable i. Instead, your loop can be controlled by num as:
enum { LIMIT = 4 * 1000 * 1000 };
num = x + y;
while( num <= LIMIT ) {
print num inside the loop, for debugging
for(i=0;i<4000000;i++)
{
num=x+y;
printf("num is %lu\n", num); /* DEBUGGING */
if(i%2==0)
sum+=num;
x=y;
y=num;
}

Recursive function to add sum of sequence of numbers and the sums thereof

This was an interview question:
Given a sequence of n numbers (n can be any number, assume n <= 100 for this question), say for eg. 11, 23, 9, 17, 20, 8, 5, 6 . Problem is to write a recursive function in C to add each number in the sequence to get the sum. If this sum is of more than one digit then sum the digits again and again if the sum is of more than one digit then sum the digits again. Follow this process until the sum is reduced to one digit no. Now add all the sums obtained in the process to output the final sum.
For illustration take above sequence: 11, 23, 9, 17, 20, 8, 5, 6
SUM(11, 23, 9, 17, 20, 8, 5, 6) = 99 => SUM(9, 9) = 18 => SUM(1, 8) = 9
Now add all the sums obtained, i.e. SUM(99, 18, 9) = 126 <== should be the output.
Please note that the function should be a recursive function in C.
Not sure about C, but the algorithm would look similar to this.
SUM(1, 2, ... n) = 1 + SUM(2, ... n) and so on to get the total, then repeat once the final number is found to be more than one digit.
Here's an Erlang implementation you could use as a guide
-module('summation').
-export([start/1]).
sumlist(List)->
lists:foldl(fun(X, Sum) -> X + Sum end, 0, List). << Inherently recursive
num_to_list(Value) ->
Str = integer_to_list(Value),
lists:map(fun(X) -> X - 48 end, Str). << Inherently recursive
accumulate([_H], List) ->
io:fwrite("~w~n", [List]),
List;
accumulate(Value, List) ->
Tmp = sumlist(Value),
accumulate(num_to_list(Tmp), [Tmp|List]). % << Recurse here
start(List)->
Value = accumulate(List, []),
sumlist(Value).
testing
25> c(summation).
{ok,summation}
26> summation:start([11, 23, 9, 17, 20, 8, 5, 6]).
[9,18,99]
126
27>
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
const int n = 8;
int sumDigits(int x)
{
int d = 0;
while (x != 0)
{
d += x % 10;
x /= 10;
}
return d;
}
int sumArr(int* a, int start)
{
return (start == n)? 0: a[start] + sumArr(a, start + 1);
}
int sum(int x)
{
return (x < 10)? x: x + sum(sumDigits(x));
}
int main(int argc, _TCHAR* argv[])
{
int* a = new int[n];
a[0] = 11; a[1] = 23; a[2] = 9; a[3] = 17; a[4] = 20; a[5] = 8; a[6] = 5; a[7] = 6;
//for (int i = 0; i < n; i++) a[i] = rand() % 100;
//for (int i = 0; i < n; i++) printf("a[%d] = %d\n", i, a[i]);
printf("sum = %d\n", sum(sumArr(a, 0)));
return 0;
}
This outputs:
sum = 126
Here's a Scala implementation:
def sum(lst: List[Int]): Int = {
val sum1 = lst.reduceLeft(_+_)
println(sum1)
sum1 match {
case nb if nb < 10 => sum1
case _ => {
val lst2 = sum1.toString.toList.map(_.toString).map(Integer.parseInt(_))
sum1 + sum(lst2)
}
}
}
val lst = List(11, 23, 9, 17, 20, 8, 5, 6)
val totalSum = sum(lst)
println(totalSum)
Result:
99
18
9
126
I'm really beginning to love, how concise Scala is.
As others had said : the point here is to understand the recursion.
There are 3 place we can use recursion :
sum all the digits in a Integral number:
sum_digital :: (Integral a) => a -> a
sum_digital d
| d < 10 = d
| otherwise = d `mod` 10 + sum_digital (d `div` 10)
chain all the sums from a start value and the rules
chain :: (Integral a) => a -> [a]
chain a
| a < 10 = [a]
| otherwise = a : chain (sum_digital a)
final one. sum of a list
mySum :: (Integral a) => [a]-> a
mySum [] = 0
mySum (x:xs) = x + mySum xs
Put all these together:
*Main> mySum $ chain $ mySum [11, 23, 9, 17, 20, 8, 5, 6]
126
The C version is left for you as the exercise:)
I just want to add this one to 77v's answer in order to make everything hardcore recursive as possible. I know this is a year ago already, and his C++ solution works quite nice already. But I really had no fun that I though I can make that one last function called sumDigits in to recursion. So to rid myself of boredom, here it is:
long sumDigits(long x, long d = 0)
{
if (x != 0)
{
d = x % 10;
return d + sumDigits(x / 10, d);
}
else
return 0;
}
It's the same, 7 lines long and accepts one argument. Note that the second one is defaulted to 0. It's used as a memory for the recursion itself. The user may ignore that second argument entirely. The function is also used the same way as 77v's implementation. You can in fact directly replace his function with this one. Hence making all the function in his solution recursion based. Which makes an already awesome work more awesome! Lol! :D
#include <iostream>
using namespace std;
class RecursiveSum {
public:
int nDigits(int a) {
int d = 0;
while (a > 0) {
d++;
a /= 10;
}
return d;
}
long sum(int *arr, int b, int e, int s) {
if (!arr)
return 0;
if (b < e) {
s += arr[b++];
return sum(arr, b, e, s);
} else { // b >= e
if (s < 10)
return s;
int nd = nDigits(s);
int* narr = new int[nd];
long n = s, itr = 0;
while (n > 0) {
narr[itr++] = n % 10;
n /= 10;
}
s += sum(narr, 0, nd, 0);
delete[] narr;
return s;
}
}
};

Resources