### Thread: Perfect Square Fibonacci program not working properly?

1. No Profile Picture
Contributing User
Devshed Newbie (0 - 499 posts)

Join Date
Oct 2011
Posts
43
Rep Power
3

#### Perfect Square Fibonacci program not working properly?

"Create a program to find out the first perfect square greater than 1 to occur in the Fibonacci sequence and display it to the console." I have no output when I enter an input.

Code:
```#include <stdio.h>
#include <math.h>

int PerfectSquare(int n);
int Fibonacci(int n);

main()
{
int i;
int number=0;

int fibNumber=0;
int psNumber=0;

printf("Enter fibonacci number:");
scanf("%i",&number);

fibNumber = Fibonacci(number);

psNumber = PerfectSquare(fibNumber);

if(psNumber != 0){
printf("%i\n",psNumber);
}
}

int PerfectSquare(int n)
{

float root = sqrt(n);
if (n == ((int) root)*((int) root))
return root;
else
return 0;
}

int Fibonacci(int n){
if (n==0) return 0;
if (n==1) return 1;
return( Fibonacci(n-1)+Fibonacci(n-2) );
}```
2. What if you'd entered 12 into your function?

main needs to return an integer.
Your PerfectSquare function returns the truncated square root of its argument. It should return 0 or n.
Using your program is tedious because you have to try numbers sequentially.
Your code shows output only on success. Guarantee a message with code like:
if (found) show(result) else show("UNFOUND");

Code:
```#include<limits.h>
#include<stdio.h>
#include<math.h>

unsigned long PerfectSquare(unsigned long n) {
unsigned long root = 0.5+sqrt(n); /* rounding avoids problem with slight underestimate. */
return n*(n == root*root);
}

unsigned long Fibonacci(unsigned long n) {
if (n < 2) return n;
return Fibonacci(n-1)+Fibonacci(n-2);
}

int main() {
unsigned long
i,
fibNumber=0,
psNumber=0;
for (i = 2; (2*fibNumber < ULONG_MAX) && (psNumber < 2); ++i) {
fibNumber = Fibonacci(i);
psNumber = PerfectSquare(fibNumber);
}
if (1 < psNumber)
printf("%lu\n",psNumber);
else
printf("none found within first %lu terms.\n",i);
return 0;
}```