Home > Mobile >  How to implement constraints in a Java program?
How to implement constraints in a Java program?

Time:06-26

I was appearing for an interview where I was required to write a program to find the largest fibonacci number below N. While I successfully got the output for a lot of test cases, my code failed for edge-test.

This is my code:

import java.util.*;
import java.lang.Math;


class LargestFibonacciNumber{
    public static void main(String args[]){
        Scanner sc = new Scanner(System.in);
        int t = sc.nextInt();
        if(t<=Math.pow(10,4)){
            while (t-->0) {
            int n = sc.nextInt();
            if(n > 0 && n<= Math.pow(10,9)){
                int result = largestFibonacciNumber(n);
            System.out.println(result);}
            
        }
        sc.close();
        }
        
    }

    static int largestFibonacciNumber(int n){
        
        
            if(n == 0){
            return 0;
        }

        int first = 0, second = 1;
        int third = first   second;

        while(third < n){
            first = second;
            second = third;
            third = first   second;
        }

        return second;
        
    }
}

This is the problem statement:

Problem Description

Given a number N, you have to find the largest Fibonacci number which is less than N.

Input Format

First line contains an integer T - Number of test cases.

Next T lines each have a given number N

Output Format

Print the answer for each test case in a separate line.

Constraints

T <= 10^4

0 < N <= 10^9

What could be the issue with my code which makes it fail the edge-test? I'm guessing it has got something to do with constraints which I'm unable to understand.

CodePudding user response:

Add a condition check for n = 1.

static int largestFibonacciNumber(int n){
    if(n == 1)
        return 0;

    int first = 0, second = 1;
    int third = first   second;

    while(third < n){
        first = second;
        second = third;
        third = first   second;
    }
    return second;
}

Then it won't fail for n = 1, also n = 0 check is not needed since N is expected to be greater than 0

CodePudding user response:

As Matt Timmermans mentiond in comments section your code returns the wrong answer for N = 1.

Your code must return 1 when the N = 1.

You must change your first if's condition to something like this:

if(n ==0 || n == 1)
    return n;

// or better way:
if(n <= 1)
    return n;
  • Related