Java, Largest prime factor - java

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]);
}
}
}

Related

Best Way to Optimize this Largest Prime Factor Program

I need some help optimizing this program. I am trying to figure out the largest prime factor for input. However, it occasionally has timeout issues, so I am interested in figuring out how to optimize it.
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class PFactor() {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t = in.nextInt();
for(int a0 = 0; a0 < t; a0++){
long n = in.nextLong();
System.out.println(pMod(n));
}
}
public static int pMod(long d) {
long maxVal = 0;
for (long i = 2; i <= d; i++) {
if (d % i == 0) {
boolean prime = pCount(i);
if (prime == true) {
max = i;
}
} else {
max = max;
}
}
return (int)max;
}
public static boolean pCount(long inLong) {
int count = 0;
for (long s = 1; s <= inLong; s++) {
if (inLong % s == 0) {
count++;
}
}
if (count == 2) {
return true;
} else {
return false;
}
}
}
Do you know how to optimize this code so that it does not have as many timeouts? I need this ready soon for something at work, so I decided to reach out to see if I could get some help, as I can't seem to figure it out myself where it needs further optimization.
I actuallly found a solution guys after a bit of tinkering with it! you were all very helpful though! Thanks for helping!

SPOJ The next Palindrome ( Java)

import java.util.*;
import java.lang.*;
class Main
{
public static void main (String[] args) throws java.lang.Exception
{
long n,a;
boolean b;
try{
Scanner sc = new Scanner(System.in);
n = sc.nextLong();
for ( long i = 0; i<n; i++){
a = sc.nextLong();
for ( long j = (a+1); j<1000000000; j++){
b = isPalindrome(j);
if ( b == true){
System.out.println(j);
break;
}
}
}
} catch ( Exception e){
return;
}
}
public static boolean isPalindrome(long n){
String intStr = String.valueOf(n);
return intStr.equals(new StringBuilder(intStr).reverse().toString());
}
}
Whats wrong with my Palindrome code?
In SPOJ, the first two test cases are compiling but for the next one and onwards it's showing the wrong answer.
First test case:
2
808
2133
output:
818
2222
The reason is that neither int neither long are big enough to store a given positive integer K of not more than 1000000 digits - 1000000 digits is well 101000000, while Long.MAX_VALUE is only 263-1.
Thus you have to use BigInteger.
The following code seems to work (no more NZEC), but it ends up with time limit exceeded.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
class Main {
public static void main(String[] args) throws java.lang.Exception {
int n = Integer.parseInt(readLine());
for (int i = 0; i < n; i++) {
BigInteger a = new BigInteger(readLine()).add(BigInteger.ONE);
if (a.signum() == -1) {
a = BigInteger.ZERO;
}
while (a.toString().length() <= 1000000) {
if (isPalindrome(a.toString())) {
System.out.println(a);
break;
}
a = a.add(BigInteger.ONE);
}
}
}
private static boolean isPalindrome(String intStr) {
int l = intStr.length();
for (int i=0, j=l-1; i < l/2+1; i++, j--) {
if (intStr.charAt(i) != intStr.charAt(j)) {
return false;
}
}
return true;
}
private static String readLine() throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
return br.readLine();
}
}

Large FIbonacci Java Time Exceeded

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));
}

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: 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