Large FIbonacci Java Time Exceeded - java

I'm stuck on a test case.
The question requires to compute a large Fibonacci number in a given period of time.
I have passed 8 cases out of 10 and stuck on 9.
Here is my Code:
import java.util.*;
import java.math.BigInteger;
public class LastNumberofFibo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
BigInteger bi = sc.nextBigInteger();
System.out.println(fib(bi));
}
public static BigInteger fib(BigInteger n) {
BigInteger val=new BigInteger("10");
int k = n.intValue();
BigInteger ans = null;
if(k == 0) {
ans = new BigInteger("0");
} else if(Math.abs(k) <= 2) {
ans = new BigInteger("1");
} else {
BigInteger km1 = new BigInteger("1");
BigInteger km2 = new BigInteger("1");
for(int i = 3; i <= Math.abs(k); ++i) {
ans = km1.add(km2);
km2 = km1;
km1 = ans;
}
}
if(k<0 && k%2==0) { ans = ans.negate(); }
return ans.mod(val);
}
}
After Submitting I get the following Time-out result.
I need help in making my code more efficient.
Feedback :
Failed case #9/10: time limit exceeded
Input:
613455
Your output:
stderr:
(Time used: 3.26/1.50, memory used: 379953152/536870912.)
Please guide me.
Yours Sincerely,
Vidit Shah

I have taken the most easy to implemement suggestions from comments and put it in code.
import java.util.*;
import java.math.BigInteger;
public class LastNumberofFibo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
BigInteger bi = sc.nextBigInteger();
System.out.println(fib(bi));
}
public static BigInteger fib(BigInteger n) {
int m = 10;
BigInteger sixty = new BigInteger("60");
int k = (n.mod(sixty)).intValue();
int ans = 0;
if(k == 0) {
ans = 0;
} else if(Math.abs(k) <= 2) {
ans = 1;
} else {
int km1 = 1;
int km2 = 1;
for(int i = 3; i <= Math.abs(k); ++i) {
ans = (km1 + km2)%m;
km2 = km1;
km1 = ans;
}
}
if(k<0 && k%2==0) { ans = -ans; }
return new BigInteger("" + ans);
}
}

Try that:
public static int fibonacci(int n) {
return (int)((Math.pow((1 + Math.sqrt(5)) / 2, n) - Math.pow((1 - Math.sqrt(5)) / 2, n)) / Math.sqrt(5));
}

Related

Co Prime Monte Carlo Simulation

Im trying to create a program to get the probability that 2 numbers are Coprime.I think my algorithm is right but I'm getting runtime errors and I can't see why.
`
import java.util.*;
import java.util.Random;
public class coPrimeMonteCarlo
{
public static void main(String[]args)
{
Scanner s1 = new Scanner(System.in);
Random rand = new Random();
double total = 0;
double totalNum = 1000000;
for(int i=0;i<totalNum;i++)
{
int a = rand.nextInt();
int b = rand.nextInt();
if(isCoPrime(a,b)==1)
{
total++;
};
}
System.out.println(total/totalNum);
}
public static int isCoPrime(int a, int b)
{
if(a==b)
{
return a;
}
else if((a == 0 || b == 0))
{
return 0;
}
else if(a>b)
{
return isCoPrime(a-b,b);
}
return isCoPrime(a,b-a);
}
}
`
Output is
at coPrimeMonteCarlo.isCoPrime(coPrimeMonteCarlo.java:35)
at coPrimeMonteCarlo.isCoPrime(coPrimeMonteCarlo.java:35)
Tried Running but got that output.

how to return in a recurssive fn in java

Actually my aim is to find the super no for eg i will be given 2 values n,k where n=148 and k =3 so i have to form p = 148148148 then add digits of p until i get a single no (ans = 3) this is what i have tried.......
import java.util.*;
public class RecurrsiveDigitSum {
public int check(int n) {
int s = 0;
int d;
while(n>0) {
d = n%10;
s = s+d;
n = n/10;
System.out.println(s);
}
if(s/10 !=0){
check(s);
}
return s;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int k = scan.nextInt();
int sum;
RecurrsiveDigitSum obj = new RecurrsiveDigitSum();
sum = obj.check(n);
System.out.println(sum);
sum = sum * k;
System.out.println(sum);
int s1 = obj.check(sum);
System.out.println(s1);
}
}
but the problem here is that even if my s = 4 finally its just returning the first value of s that has been found so pls help me friends
you must put return before recursive calling.
if(s/10 !=0){
return check(s);
}
If you don't put it, the result of calling function will be loss and the result of s will be returned instead of check(s).
I've improved your solution little bit.
public int check(int n) {
int s = 0;
while(n>0) {
s += n%10;
n /= 10;
}
if(s/10 != 0){
return check(s);
}
return s;
}

Recursive Coin Change Making by printing all possible ways

I have tried to print all the paths which give the given amount. But my code does not work properly. I think I am missing some points to print all possible combinations. For example;
if amount: 7 and startCoin = 25, the program needs to give me:
{5,1,1} and {1,1,1,1,1,1,1}.
Can you help me to fix these problem?
Note: Preferably Java Solutions
class Solution {
static int[] coinSet = {1,5,10,25};
static List<List<Integer>> possibleWays = new ArrayList<>();
static List<Integer> currentWay = new ArrayList<>();
private static int makeChange(int amount, int startCoin){
boolean flag = false;
for(int i =0 ; i < coinSet.length ; i++){
if(coinSet[i] == startCoin) {
flag =true;
}
}
if(!flag){
throw new IllegalArgumentException("startCoin has to be in the specified range");
}
int nextCoin = 0;
switch(startCoin) {
case 25:
nextCoin = 10;
break;
case 10:
nextCoin = 5;
break;
case 5:
nextCoin = 1;
break;
case 1:
possibleWays.add(currentWay);
currentWay = new ArrayList<>();
return 1;
}
int ways = 0;
for(int count = 0; count * startCoin <= amount; count++){
ways += makeChange(amount - (count * startCoin),nextCoin);
}
return ways;
}
public int calculateNumberOfWays(int amount, int startCoin) throws Exception {
if (amount == 0) {
throw new Exception(); }
return makeChange(amount, startCoin);
}
public static void main(String[] args) {
System.out.println(makeChange(5,25));
System.out.println(possibleWays);
}
}
This can be solved using backtracking but that is not very efficient, below is the working java code
/**
* Created by sumit sharma on 3/1/2016.
*/
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
public class Main {
static int[] coinSet = {1,5,10,25};
static List<List<Integer>> possibleWays = new ArrayList<>();
static List<Integer> currentWay = new ArrayList<>();
public static void main(String[] args) {
List<Integer> countOfCoins = new ArrayList<>();
makeChange(7, 0, countOfCoins);
//System.out.print(possibleWays);
}
private static int makeChange(int amount, int startCoinIdx, List<Integer> coinsSoFar) {
if(startCoinIdx == coinSet.length){
if(amount == 0){
possibleWays.add(coinsSoFar);
System.out.println(coinsSoFar);
}
//System.out.println(coinsSoFar);
return 0;
}
for(int count = 0;(count*coinSet[startCoinIdx]) <= amount;count++){
List<Integer> temp = new ArrayList<>();
for(int i = 0;i < coinsSoFar.size();i++) temp.add(coinsSoFar.get(i));
for(int i = 0;i < count;i++) temp.add(coinSet[startCoinIdx]);
makeChange(amount - (count * coinSet[startCoinIdx]),startCoinIdx+1, temp);
temp.clear();
}
return 0;
}
}
Link to solution on Ideone : http://ideone.com/kIckmG

Java, Largest prime factor

I'm trying to solve this question:
https://www.hackerrank.com/contests/projecteuler/challenges/euler003/submissions/code/2977447
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of a given number N?
Input Format
First line contains T, the number of test cases. This is followed by T lines each containing an integer N.
Output Format
For each test case, display the largest prime factor of N.
Constraints
1≤T≤10
10≤N≤1012
and my code below gets a timeout error for the fifth test (which we don't know about the actual content). any thought why did it fail the test? thanks
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Collections;
import java.util.Scanner;
/* Author: Derek Zhu
* 1and1get2#gmail.com
* https://www.hackerrank.com/contests/projecteuler/challenges/euler003
* */
// The part of the program involving reading from STDIN and writing to STDOUT has been provided by us.
public class Solution {
public static boolean D = true;
static BufferedReader in = new BufferedReader(new InputStreamReader(
System.in));
static StringBuilder out = new StringBuilder();
public static void main(String[] args) throws NumberFormatException,
IOException {
int numOfCases = Integer.parseInt(in.readLine());
for (int i = 0; i < numOfCases; i++){
calculateCase(Long.parseLong(in.readLine()));
}
}
private static void calculateCase(Long input) throws IOException{
if (D) System.out.println("Processing: " + input);
long largestPF = prime(input);
if (D) System.out.print("Final calculate: ");
System.out.println(largestPF);
}
private static long prime(long n){
long i = 2;
while ( n % i != 0 && i < n){
i ++;
}
if (D) System.out.println("found i: " + i);
if (i < n){
return prime(n/i);
} else {
return n;
}
}
public static int primeFactors(BigInteger number) {
BigInteger copyOfInput = number;
int lastFactor = 0;
for (int i = 2;
BigInteger.valueOf(i)
.compareTo(copyOfInput) <= 0; i++) {
if (copyOfInput.mod(BigInteger.valueOf(i))
.compareTo(BigInteger.ZERO) == 0)
{
lastFactor = i;
copyOfInput = copyOfInput
.divide(BigInteger.valueOf(i));
i--;
}
}
return lastFactor;
}
}
Thanks #ajb
as it turns out, taking another method would be much efficient.
private static long method2(long NUMBER){
long result = 0;
for(int i = 2; i < NUMBER; i++) {
if(NUMBER % i == 0 && isPrime(NUMBER / i)) {
result = NUMBER / i;
break;
}
}
return result;
}
private static boolean isPrime(long l) {
for(long num = 2, max = l / 2 ; num < max; num++) {
if(l % num == 0) {
return false;
}
}
return true;
}
complete code with comparison of time can be found here:
https://github.com/1and1get2/hackerrank/blob/master/Contests/ProjectEuler%2B/003_LargestPrimeFactor/src/Solution.java
if (NUMBER<2){
return -1;
}
int result = 0;
for (int i =2; NUMBER>i; i++ ){
if (NUMBER%i==0){
result = NUMBER / i;
if (result/1==result && result/result==1 && result%2!=0 && result%3!=0 && result%5!=0 && result%7!=0){
break;
}
}
}
return result;
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t = in.nextInt();
int count,k=0,n=0;
long arr[]=new long[1000000];
long arr1[]=new long[1000000];
long arr2[]=new long[10000000];
for(int a0 = 0; a0 < t; a0++){
arr[a0] = in.nextLong();
}
for(int i=0;i<t;i++)
{
for(int j=2;j<=arr[i];j++)
{
if(arr[i]%j==0)
{
arr1[k]=j;
k++;
}
}
for(int l=0;l<k;l++)
{
count=0;
for(int m=1;m<=arr1[l];m++)
{
if(arr1[l]%m==0)
{
count++;
}
}
if(count==2)
{
arr2[n]=arr1[l];
n++;
}
}
Arrays.sort(arr2);
System.out.println(arr2[arr2.length-1]);
}
}
}

Java: check if number belongs to Fibonacci sequence

I'm supposed to write a code which checks if a given number belongs to the Fibonacci sequence. After a few hours of hard work this is what i came up with:
public class TP2 {
/**
* #param args
*/
public static boolean ehFibonacci(int n) {
int fib1 = 0;
int fib2 = 1;
do {
int saveFib1 = fib1;
fib1 = fib2;
fib2 = saveFib1 + fib2;
}
while (fib2 <= n);
if (fib2 == n)
return true;
else
return false;
}
public static void main(String[] args) {
int n = 8;
System.out.println(ehFibonacci(n));
}
}
I must be doing something wrong, because it always returns "false". Any tips on how to fix this?
You continue the loop while fib2 <= n, so when you are out of the loop, fib2 is always > n, and so it returns false.
/**
* #param args
*/
public static boolean ehFibonacci(int n) {
int fib1 = 0;
int fib2 = 1;
do {
int saveFib1 = fib1;
fib1 = fib2;
fib2 = saveFib1 + fib2;
}
while (fib2 < n);
if (fib2 == n)
return true;
else
return false;
}
public static void main(String[] args) {
int n = 5;
System.out.println(ehFibonacci(n));
}
This works. I am not sure about efficiency..but this is a foolproof program,
public class isANumberFibonacci {
public static int fibonacci(int seriesLength) {
if (seriesLength == 1 || seriesLength == 2) {
return 1;
} else {
return fibonacci(seriesLength - 1) + fibonacci(seriesLength - 2);
}
}
public static void main(String args[]) {
int number = 4101;
int i = 1;
while (i > 0) {
int fibnumber = fibonacci(i);
if (fibnumber != number) {
if (fibnumber > number) {
System.out.println("Not fib");
break;
} else {
i++;
}
} else {
System.out.println("The number is fibonacci");
break;
}
}
}
}
you can also use perfect square to check whether your number is Fibonacci or not. you can find the code and some explanation at geeksforgeeks.
you can also see stackexchange for the math behind it.
I'm a beginner but this code runs perfectly fine without any issues. Checked with test cases hopefully it'll solve your query.
public static boolean checkMember(int n) {
int x = 0;
int y = 1;
int sum = 0;
boolean isTrue = true;
for (int i = 1; i <= n; i++) {
x = y;
y = sum;
sum = x + y;
if (sum == n) {
isTrue=true;
break;
} else {
isTrue=false;
}
}
return isTrue;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
System.out.print(checkMember(n));
}

Categories