Fibonacci One Recursive Call - c

I wish to transform the basic Fibonacci function:
int find_fib(int fib_to) {
if (fib_to == 0) {
return 0;
}
else if (fib_to == 1) {
return 1;
}
else {
return (find_fib(fib_to - 1) + find_fib(fib_to - 2));
}
}
into one that would use only ONE recursive call. I searched up many sites that tells me to store the value found by (find_fib(fib_to - 1) + find_fib(fib_to - 2)) into some array and then make use of the array, but doing so requires 2 recursive calls.
Any tips on how to solve the problem?

You mean something like that?
#include <stdio.h>
int fibonacci(int number_iterations, int number_a, int number_b)
{
if(number_iterations <= 0) {
printf("error: 'number_iterations' must be >= 1\n");
return -1;
}
if(number_iterations == 1) {
printf("%d ", number_a + number_b);
return number_a + number_b;
}
printf("%d ", number_a + number_b);
return fibonacci(number_iterations - 1, number_b, number_a + number_b);
}
int main()
{
int a = 1;
int b = 1;
int number_of_iterations = 0;
printf("Enter a number >= 1: ");
int err = scanf("%d", &number_of_iterations);
int final_result = -1;
if (err != EOF) {
printf("fibonacci: %d %d ", a, b);
final_result = fibonacci(number_of_iterations, a, b);
}
printf("Final fibonacci: %d\n", final_result);
return 0;
}
would return you:
Enter a number >= 1: 10
fibonacci: 1 1 2 3 5 8 13 21 34 55 89 144
Final fibonacci: 144

Related

Checking whether space should be printed in the middle or at the end in for loop?

I am trying to give info to my program whether it should print space or not.
My code looks something like this, and its printing spaces at the end (which is not what I want)
void function(int given_limit)
{
int current_num = 2;
while (given_limit > 1)
{
if (given_limit % current_num == 0)
{
if (current_num == 2)
{
printf("%d ", current_num);
}
else if (current_num == 3)
{
printf("%d ", current_num);
}
else if (current_num == 5)
{
printf("%d ", current_num);
}
else if (current_num == 7)
{
printf("%d ", current_num);
}
else
{
printf("%d ", current_num);
}
given_limit /= current_num;
}
else
current_num++;
}
printf("\n");
}
In main() I am calling it something like this:
int main()
{
int given_limit = 13;
for (int i = 0; i <= given_limit; i++)
{
printf("%d\t\t", i);
function(i);
}
}
I would appreciate any tips and help.
One of the ideas is maybe to store it in an array.
I replaced spaces with asterisks for better visibility and removed the redundant if-elements. Then I introduced a flag which indicates whether it is the output of the first factor or a later one. In front of each later one we put the space (or asterisk).
#include <stdio.h>
#include <stdbool.h>
void function(int given_limit)
{
bool is_first_factor = true;
int current_num = 2;
while (given_limit > 1)
{
if (given_limit % current_num == 0)
{
if (is_first_factor) {
is_first_factor = false; // not first anymore
// print nothing
} else {
printf("*"); // between two factors
}
printf("%d", current_num);
given_limit /= current_num;
}
else
current_num++;
}
printf("\n");
}
int main(int argc, char **argv)
{
int given_limit = 13;
for (int i = 0; i <= given_limit; i++)
{
printf("%d\t\t", i);
function(i);
}
}
$ gcc spacing.c
$ ./a.out
0
1
2 2
3 3
4 2*2
5 5
6 2*3
7 7
8 2*2*2
9 3*3
10 2*5
11 11
12 2*2*3
13 13
$
As mentioned above move the space character to in front of each prime factor and then align the output to take the initial starting space character into account.
This example also skips unnecessary factors.
/* primefactors.c
*/
#include <stdio.h>
void primeFactors(int number)
{
printf(" %2d ", number);
// only test factors <= sqrt(number)
// skip even factors > 2
int factor = 2;
while (factor <= number / factor) {
if (number % factor == 0) {
printf(" %d", factor);
number /= factor;
}
else if (factor == 2){
factor = 3;
}
else {
factor += 2;
}
}
// at this point number equals the greatest prime factor
printf(" %d\n", number);
}
int main (void)
{
int max = 45;
printf("\nnumber prime factors\n");
printf("------ -------------\n");
// skip 0 and 1 which have no prime factors
printf(" %2d\n", 0);
printf(" %2d\n", 1);
for (int i = 2; i <= max; ++i) {
primeFactors(i);
}
return 0;
}

why when I input any number between 14 and 20, the output is incorrect?

'I need to calculate and print an upside down pascal triangle, so I wrote down 2 functions for factorial and for the nCr, and I have followed, the equation x! / (y! * (x - y)!)'
#include <stdio.h>
#include <stdlib.h>
int Factorial (int value)
{
if (value == 1 || value == 0)
{
return 1;
}
return value*Factorial(value - 1);
}
int nCr(int value, int r)
{
return Factorial(value)/(Factorial(r) * Factorial(value - r));
}
int main(int argc, char **argv)
{
int value, i, j, k;
char* p;
value = strtol(argv[1], &p, 10);
if (*p != '\0')
{
return 1;
}
if (argc != 2)
{
return 1;
}
if (value < 1 || value > 20)
{
printf("Error: Please enter a value between 1 and 20 inclusively\n");
return 1;
}
else
'The problem is supposed to be in the nested loops I guess'
{
for (i = value - 1; i >= 0; i--)
{
for (j = value - i; j > 0; j--)
{
printf(" ");
}
for (k = 0; k <= i; k++)
{
printf("%d ", nCr(i, k));
}
printf("\n");
}
}
return 0;
}
The problem was in the declaration of the Factorial functions, as int type would overflow if the input is more than 13!, so we should declare the Factorial function as long, so that it does not overflow.

Is it possible to create a program that accepts 3 integers and outputs the odd/even integers without using array?

Our teacher gave us an exercise in C. We have to create a program that accepts three integers and outputs them if they are odd or even without using arrays, only loops and conditional statements can be used.
What I am only allowed to use are scanf(), printf(), loops and conditional statements. I must not have multiple variables like odd1, odd2, odd3, even1, even2, even3.And I must not do scanf("%d %d %d",), so I must run scanf("%d") three times in a loop.I couldn't think of any idea that would precisely print the same format of the expected output. I hope someone could help me on this
#include <stdio.h>
int main() {
int i, num;
printf("Enter three integers: ");
for(i=1;i<=3;i++)
{
scanf("%d", &num);
if(!(num%2))
{
printf("\nEven: %d", num);
}
if(num%2)
{
printf("\nOdd: %d\n", num);
}
}
}
I expect the following like this...
Input:
1 2 3
Output:
Odd: 1 3
Even: 2
Input:
2 4 6
Output:
Odd:
Even: 2 4 6
...but the only thing i can do is this
Input:
1 2 3
Output:
Odd: 1
Even: 2
Odd: 3
Input:
1 3 5
Output:
Odd: 1
Odd: 3
Odd: 5
Recursion (loop in disguise) for the win (if you don't mind having the even numbers reversed).
#include <stdio.h>
#include <stdlib.h>
void separate(int m, int n) {
if (m == n) printf("Odd:");
if (n == 0) { printf("\nEven:"); return; }
int i;
if (scanf("%d", &i) != 1) exit(EXIT_FAILURE);
// print odd numbers before recursing; even numbers after recursing
if (i % 2 == 1) printf(" %d", i);
separate(m, n - 1);
if (i % 2 == 0) printf(" %d", i);
if (m == n) printf("\n\n");
}
See https://ideone.com/GpE7rC which includes the calling and input
separate(3, 3); // for 3 numbers
One way would be say:
int odd1, odd2, odd3, numOdd = 0;
/* Code as above */
scanf("%d", &num);
if (num%2)
{
if (numOdd == 0)
{
odd1 = num;
numOdd++;
}
else if (numOdd == 1)
{
odd2 = num;
numOdd++;
}
/* And continue */
}
else
{
/* Repeat with even1, even2, even3 and numEven */
}
/* Print out numOdd oddn's */
/* Print out numEven evenn's */
It seems a silly exercise, but at least you'll get a lot of practise writing if statements...
I also thought:
scanf("%d", &num1);
scanf("%d", &num2);
scanf("%d", &num3);
Might be shorter, but then you don't need a for loop, unless you do something like:
printf("Odd: ");
for (i = 0; i < 3; i++)
{
int thisNum;
if (i == 0) thisNum = num1;
else if (i == 1) thisNum = num2;
/* etc */
if (thisNum % 2) printf("%d ", thisNum);
}
The problems is that you cannot use arrays. Hence you must not use strings, which are arrays. Allowing the use of scanf and printf is a deliberate trap set by your teacher - there is no way of using them in an useful way without resorting to use of arrays, explicit or implied.
Therefore you must do this:
#include <stdio.h>
#include <ctype.h>
void print_number(int n)
{
if (n < 0) {
putchar('-');
n = -n;
}
if (n == 0)
putchar('0');
if (n / 10)
print_number(n / 10);
putchar(n % 10 + '0');
}
int main(void) {
putchar('E');
putchar('n');
putchar('t');
putchar('e');
putchar('r');
putchar(' ');
putchar('t');
putchar('h');
putchar('r');
putchar('e');
putchar('e');
putchar(' ');
putchar('i');
putchar('n');
putchar('t');
putchar('e');
putchar('g');
putchar('e');
putchar('r');
putchar('s');
putchar(':');
putchar(' ');
fflush(stdout);
int odd1, odd2, odd3, odd_count = 0;
int even1, even2, even3, even_count = 0;
for(int i = 0; i < 3; i++)
{
int number = 0;
int c;
while (1) {
c = getchar();
if (isspace(c)) {
if (c == '\n')
break;
while ((c = getchar()) == ' ');
ungetc(c, stdin);
break;
}
else if (isdigit(c)) {
number = number * 10 + c - '0';
}
}
if (number % 2) {
switch (odd_count) {
case 0: odd1 = number; break;
case 1: odd2 = number; break;
case 2: odd3 = number; break;
}
odd_count ++;
}
else {
switch (even_count) {
case 0: even1 = number; break;
case 1: even2 = number; break;
case 2: even3 = number; break;
}
even_count ++;
}
}
putchar('O');
putchar('d');
putchar('d');
putchar(':');
putchar(' ');
if (odd_count >= 1) {
print_number(odd1);
}
if (odd_count >= 2) {
putchar(' ');
print_number(odd2);
}
if (odd_count >= 3) {
putchar(' ');
print_number(odd3);
}
putchar('\n');
putchar('E');
putchar('v');
putchar('e');
putchar('n');
putchar(':');
putchar(' ');
if (even_count >= 1) {
print_number(even1);
}
if (even_count >= 2) {
putchar(' ');
print_number(even2);
}
if (even_count >= 3) {
putchar(' ');
print_number(even3);
}
putchar('\n');
}
This code does not use any arrays.
If you cannot define any functions (other than main obviously), you must inline the print_number in the 6 places changing the recursion into iteration. Good luck!
If the teacher however accepts the use of strings in a task that does not allow the use of arrays, you can take it as a license to disregard all silly restrictions set by them.
Given the fact that you are learning C, perhaps your teacher wants to teach you some pointer arithmetics instead of using arrays like in this code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i = 0;
int *odd = (int*)malloc(3 * sizeof(int));
int odd_count = 0;
int *even = (int*)malloc(3 * sizeof(int));
int even_count = 0;
printf("Enter three integers: ");
for(i=0; i<3; i++)
{
int num = 0;
scanf("%d", &num);
if(!(num%2))
{
*even++ = num;
even_count++;
}
if(num%2)
{
*odd++ = num;
odd_count++;
}
}
even -= even_count;
odd -= odd_count;
printf("\nEven: ");
for(i=0; i<even_count; i++)
{
printf("%d ", *even++);
}
printf("\nOdd: ");
for(i=0; i<odd_count; i++)
{
printf("%d ", *odd++);
}
free(odd);
free(even);
return 0;
}

Need 10 outputs per line

I am having trouble refining some code. My code takes a number "n" and calculates that many prime numbers. I need to display 10 primes per line of output data. Any tips would be appreciated.
#include <stdio.h>
int main()
{
int n, i = 3, count, c;
printf("How many primes would you like?");
scanf("%d",&n);
if ( n >= 1 )
{
printf("2");
}
for ( count = 2 ; count <= n ; )
{
for ( c = 2 ; c <= i - 1 ; c++ )
{
if ( i%c == 0 )
break;
}
if ( c == i )
{
printf(" %d",i);
count++;
}
i++;
}
return 0;
}
Just try
printf(" %5d", i);
/* ^ to help align the numbers
and
if ((count + 1) % 10 == 0)
fputc(stdout, '\n');
fix for the first time when you already print 2.
bool is_prime(int anyNum) //takes an integer array returns, is_prime
{
bool is_prime = true;
for (int c = 2; c <= anyNum - 1; c++)
{
if (anyNum % c == 0)
{
//printf("%d is not prime\r\n" , anyNum);
is_prime = false;
}
}
return is_prime;
}
int main()
{
int num_primes;
printf("How many primes would you like: ");
std::cin >> num_primes;
printf("\r\nScanned Primes Are---\r\n");
int foundPrimes = 0;
int x = 0;
for (; x <= num_primes; x++)
{
bool gotLuckyFindingPrime = is_prime( x );
if (gotLuckyFindingPrime)
{
if (foundPrimes % 10 == 0)
{
printf("\r\n");
}
printf(" %d", x);
foundPrimes = (foundPrimes + 1) % 10;
}
}
}
Does handle ten digit showing on cmd too, you can experiment with formatting

value returned from a function is not same as received. Why?

I am returning values 1 or 0 from function isprime(0 when it is not prime and 1 when it is prime) but when i print the returned value of x(return value of isprime) it is not same as what I returned from isprime. Why?
#include<stdio.h>
int isprime(int b);
main()
{
int a,rem,i;
printf("enter the number");
scanf("%d", &a);
for(i = 1; i < a; i++)
{
rem = a % i;
if(rem == 0)
{
int x = isprime(i);
printf(" value of x returned for i = %d is %d", i, x);
if(x = 1)
{
printf("%d\n", i);
}
}
}
return (0);
}
/**
*
*returns 1 if b is prime else returns 0
*/
int isprime(int b)
{
int x, count = 0;
printf("input recieved %d \n", b);
for(x = 1; x <= b; x++)
{
if (b % x == 0)
{
count = count + 1;
}
printf("the value of count is %d\n", count);
}
if(count == 2) {
printf("returning the value as 1\n");
return 1;
}
else {
printf("returning the value as 0\n");
return 0;
}
}
if(x = 1)
= is assignment. You need == operator instead. You are doing correct in other if conditions though.
Also, the logic of calculating prime numbers is inefficient. You can break the loop once the count is greater than 2.
if (b % x == 0)
{
count = count + 1;
if (count > 2)
{
// This ensures you are returning correct value later.
break;
}
}
Have a look at this algorithm: Sieve of Eratosthenes
This answer is correct.
For removing such kind of mistakes use it like
if(1=x)
using this approach you can avoid such behavior.
Here I am just approaching to avoid typo mistakes.

Resources