Niuke Exam Questions Review

topic

[Fibonacci Number] The Fibonacci number series is defined as this:
f [0] = 0
f [1] = 1
for EACH I ≥ 2: f [i] = f [i-1] + f [i-2]
. We call the Fibonacci number. Give you an N, you want to change it into a Fibonacci number, you can change the current number X into X-1 or X+1 at each step
, now give you a number N and find the minimum number of steps needed to become a Fibonacci number.
Enter a description:

The input is a positive integer N(1 ≤ N ≤ 1,000,000)

Output description:

Output a minimum number of steps into Fibonacci number"

Example 1:
Enter:

15

output:

2

Answer

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<math.h>
int main()
{
    
    
	int n = 0;
	scanf("%d", &n);
	int f1 = 0;
	int f2 = 1;
	int f3 = f2 + f1;       
	while (1)
	{
    
    
		if (n == f2)
		{
    
    
			printf("0\n");     //因为输入的n大于等于1,所以n也可能一开始等于f2,n=f2就只需要0步变换
		}
		else if (n < f2)     
		{
    
    
			if (abs(n - f2) < abs(n - f1))              //abs为求绝对值函数
			{
    
    
				printf("%d\n", abs(n - f2));
			}
			else
			{
    
    
				printf("%d\n", abs(n - f1));
			}
		}
		f1 = f2;                //n大于f2,循环会一直执行下去,直到n处于f1跟f2之间,随后做差求出最小的步数
		f2 = f3;
		f3 = f1 + f2;
	}
	return 0;
}

insert image description here

first contact ideas

#include<stdio.h>
int main()
{
    
    
int n=0;
int a=1;
int i=0;
int num=1;
int arr[10000]={
    
    0};
int j=0;
int y=0;
scanf("%d",&n);
for(i=0;num<=1000000;i=y)       //Fibonacci数列一个一个找出来放入数组
{
    
    
y=num;
num+=i;
arr[j]=num;
j++;
}
int c=0;
for(c=0;c<j-1;c++)      //遍历数组对比
if((arr[c]<=n)&&(arr[c+1]>=n))
{
    
    
printf("%d\n",((n-arr[c])>(arr[c+1]-n))?(arr[c+1]-n):(n-arr[c]));
}
return 0;
}

First find out the Fibonacci sequence one by one, and then traverse the arrays and compare them one by one, which is indeed blind and troublesome.

Guess you like

Origin blog.csdn.net/st200112266/article/details/127500823