I am working on the Project Euler #25. I am intending to save all fibonacci number in a BigInteger array. However, there throws a NullPointerException, I don't know why and how to avoid it. I know there is much more simple algorithm to solve this question. But I just want to know where is my mistake, thank you very much! Here is the question states: The Fibonacci sequence is defined by the recurrence relation:
Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1. Hence the first 12 terms will be:
F1 = 1 F2 = 1 F3 = 2 F4 = 3 F5 = 5 F6 = 8 F7 = 13 F8 = 21 F9 = 34 F10 = 55 F11 = 89 F12 = 144 The 12th term, F12, is the first term to contain three digits.
What is the first term in the Fibonacci sequence to contain 1000 digits?
My code is below:
private static BigInteger[] fibonacci;
public static void main(String[] args) {
for(int i = 0; fibonacci[fibonacci.length-1].toString().length() < 1000; i++){
if(i == 0)
fibonacci[i] = BigInteger.ZERO;
if(i < 3)
fibonacci[i] = BigInteger.valueOf(1);
else
fibonacci[i] = fibonacci[i - 1].add(fibonacci[i - 2]);
}
System.out.println(fibonacci.length);
}
You have not initialized the array fibonacci. You need to allocate memory before using the array.
private static BigInteger[] fibonacci = new BigInteger[1000]; // Some number x
I would recommend using a List instead of an array given that you don't know the size of array.
private static List<BigInteger> fibonacci = new ArrayList<BigInteger>();
Also, if you are using arrays, fibonacci[fibonacci.length - 1] will not work because you are always checking for position 999 if you're initializing array size to 1000. For this to work, you have to use an ArrayList and then you can use
fibonacci[fibonacci.size() - 1]
You never initialized your fibonacci array.
Just use
private static BigInteger[] fibonacci = new BigInteger[1000]();
or better extract the amount of Fibonacci numbers you want to calculate to a separate constant:
private static int amount = 1000;
private static BigInteger[] fibonacci = new BigInteger[amount]();;
public static void main(String[] args) {
for(int i = 0; i < amount; i++){
if(i == 0)
fibonacci[i] = BigInteger.ZERO;
else if(i < 3)
fibonacci[i] = BigInteger.valueOf(1);
else
fibonacci[i] = fibonacci[i - 1].add(fibonacci[i - 2]);
}
System.out.println(fibonacci.length);
Related
I want to split a integer number in groups of two without using arrays and math library, eg 1245 into 12 and 45 and 123 into 01 and 23. I thought about /100 and % 100, eg 2330 => 23 30 but that method depends on the number of digits...
I expect to get groups of two
Here is a convert to string, slice, and convert back approach:
import java.util.ArrayList;
public static void main(String[] args)
{
ArrayList<Integer> pairs = new ArrayList<Integer>();
int n = 1234567;
String s = Integer.toString(n);
int start = 0;
if(s.length() % 2 == 1)
{
start = 1;
pairs.add(Integer.parseInt(s.substring(0,1)));
}
for(int i = start; i < s.length()-1; i+=2)
{
pairs.add(Integer.parseInt(s.substring(i,i+2)));
}
//test:
for(int p : pairs)
{
System.out.println(p);
}
}
Output:
1
23
45
67
for my home work i need to write code to calculate 2 power n (2^n)
while i managed to make it work for n from 0 to 30, for 31 i get -2147483648
and for any n above 31 (33,35,40..) i just get 0.. how can i take care of it?
i need to use simple commands i cant use math pow
public class Task3a {
public static void main(String[] args) {
//---------------write your code BELOW this line only!--------------
Scanner myScanner = new Scanner (System.in);
int n = myScanner.nextInt();
int expo = n ;
int base = 2;
if (n==0){
System.out.println("1");
}
if (n==1){
System.out.println(base);
}
else{
while(expo>1){
base = base * 2 ;
expo = expo - 1;
}
System.out.println(base);
}
//---------------write your code ABOVE this line only!--------------
}
}
as i said , for an example for 2^35 i get 0
You need to switch to use the primitive long. The primitive int has a limited value of 2^(+/-)31 so it is defaulting to zero once it has that limit.
Use BigInteger . So 2^35 is:
BigInteger base = new BigInteger("2");
int power = 35;
BigInteger answer = base.pow(power);
System.out.println(answer.toString());
I'm creating a "roulette wheel" for a programming class assignment. This wheel generates random numbers from 0 to 36 using Math.random. One part of the assignment is to add "double zero" (00) as a possible output. Is it possible to do so through this equation?
spin = (int) (Math.random()*(37 - 0)) + 0;
Assuming you want 00 and 0 to be a separate output, you will need to get a String instead, as integers treat the two as the same value. An option I thought of is to use a 39th possible output. You could add this in your code below:
String getSpin() {
int spin = (int)(Math.random() * 38);
if (spin == 38) return "00";
else return Integer.toString(spin);
}
When you want to print 00 you should take 0 convert it to string and add "0" to it and print it as 00 and in the application logic use only one 0 and make the app give it double change of hitting it
"00" can be NOT integer in Java so we can use String type for "00".
I thought we can prepare String array contains numbers as string from 00 to 36, then generate random number from 0 to 37 because length of string array is 38.
And then get a value from array at position for the random number.
I coded and put it in this answer, hope it can help you.
Cheers your assignment.
public static void main(String[] args) {
// Generate numbers as String from 00 to 36
String numbers[] = new String[38];
numbers[0] = "00";
for(int i=1; i<numbers.length; i++) {
numbers[i] = Integer.toString(i-1);
}
// Generate random number
int min = 0;
int max = numbers.length - 1;
int randomNum = min + (int)(Math.random() * ((max - min) + 1));
// Return number at a position of randomNum
System.out.println("Output: " + numbers[randomNum]);
}
I have been trying to finish this for a couple of hours now. My program is supposed to generate random numbers due to the users input. Then the program divide the numbers in two new even and odd arrays. I have solved the "generated random numbers" part but now i need too transfer the even and odd numbers into two new arrays.
This is what the output should look like:
How many random numbers between 0 - 999 do you want? **12**
Here are the random numbers:
145 538 56 241 954 194 681 42 876 323 2 87
These 7 numbers are even:
538 56 954 194 42 876 2
These 5 numbers are odd:
145 241 681 323 87
This is my code at the moment:
import java.util.Scanner;
public class SlumpadeTal {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Hur många slumptal i intervallet 0 - 999 önskas?");
int antal = input.nextInt();
System.out.println("Här är de slumpade talen:");
int[] arrayen = new int[antal];
for (int i = 0; i < arrayen.length; i++) {
arrayen[i] = (int) (Math.random() * 999 + 1);
System.out.print(arrayen[i] + " ");
if ((arrayen[i] % 2) == 0) {
}
}
}
}
NOTE that i can't use any class for this. such as Arraylist, Vector or others!
A simple solution would be to count to number of even numbers and odd numbers,
create arrays of those sizes, and once again iterate over your original array to put each number in it's place.
edit: something like this:
int evenCounter = 0;
int oddCounter = 0;
Scanner input = new Scanner(System.in);
System.out.println("Hur många slumptal i intervallet 0 - 999 önskas?");
int antal = input.nextInt();
System.out.println("Här är de slumpade talen:");
int[] arrayen = new int[antal];
for (int i = 0; i < arrayen.length; i++) {
arrayen[i] = (int) (Math.random() * 999 + 1);
System.out.print(arrayen[i] + " ");
if ((arrayen[i] % 2) == 0) {
evenCounter++;
}
else
oddCounter++;
}
}
int[] evenArray = new int[evenCounter];
int[] oddArray = new int[oddCounter];
evenCounter = 0;
oddCounter = 0;
for (int i =0; i < arrayen.length; i++){
if ((arrayen[i] % 2) == 0) {
evenArray[evenCounter] = arrayen[i];
evenCounter++;
}
else{
oddArray[oddCounter] = arrayen[i];
oddCounter++;
}
}
My solution will be divide the number into odd or even number after a number is generated. Using arraylist will be better than array because its capacity will be grow automatically and it is suitable for your case because you dont know how many even number or odd number will be generate for each time.
The if-statement you have in your code (if ((arrayen[i] % 2) == 0)) is correct.
What I suggest doing is instead of creating new arrays, create a collection type that has a dynamic length, such as an ArrayList. That way you don't have to worry about figuring out the size first, and thus don't have to iterate twice.
If you really need an array for whatever reason, you can always convert the ArrayList to an array with ArrayList#toArray(T[])
I am working on a very simple spoj problem in which we have to take input N calculate its factorial then find out number of trailing zeros and display it some thing like
Sample Input:
6
3
60 // fact of 60 has 14 trailing zeros
100
1024
23456
8735373
Sample Output:
0
14
24
253
5861
2183837
so i have written a code which is working fine on my machine but when i am submitting it is giving me time limit error. i don't know how to make this code fast. So i want suggestions from you guys.
public class Factorial {
public static void main(String[] args) throws IOException {
try {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(bf.readLine());
for (int i = 0; i < t; i++) {
Long num = Long.parseLong(bf.readLine());
BigInteger bd = BigInteger.valueOf(num);
System.out.println(countTrailinZeros(factorial(bd.toString())));
}
} catch (IllegalStateException e) {
return;
}
}
public static BigInteger factorial(String n) {
BigInteger x = BigInteger.valueOf(1);
for (long i = 1; i <= Integer.parseInt(n); i++) {
x = x.multiply(BigInteger.valueOf(i));
}
return x;
}
public static int countTrailinZeros(BigInteger bd) {
String s = bd.toString();
int glen = s.length();
s = s.replaceAll("[0.]*$", "");
int llen = s.length();
return glen - llen;
}
}
I have googled about some possible solutions and found out that lookup table may work i don't have much idea about this. I'd be very thankful if some can explain me about lookup table.
edit: Could it be java is too slow to solve this problem in given time? or in general it is not favorable to use java for competitive programing?
you dont need to calculate factorial to get number of trailing zeroes.
Solution :
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int lines = Integer.parseInt(br.readLine());
int sum, N, p;
for (int i = 0; i < lines; i++) {
N = Integer.parseInt(br.readLine());
sum = 0;
p = 5;
while (N / p != 0) {
sum = sum + N / p;
p = p * 5;
}
System.out.println(sum);
}
}
}
Logic is :
The highest power of a prime number p in N! is given by
floor(N/p) + floor(N/p*p) + floor(N/p*p*p) ... so on till [floor(N/p^n) = 0]
so since number of ending zeroes is required , ans = min(max power of 2 in N!, max power of 5 in N!)
because zeroes appears on multiplication by ten and ten can be decomposed to 10 = (2 * 5).
It is fine to assume that max power of 5 in N! is always less than max power of 2 in N!.
as multiples of 2 occur more frequently than multiples of 5.
So problem reduces to finding max power of 5 in N! and hence the solution.
Example :
N = 5
max power of 5 in 5! = floor(5/5) + floor(5/25) => 1 + 0 => ans = 1
N = 100
max power of 5 in 100! = floor(100/5) + floor(100/25) + floor(100/125) => 20 + 4 + 0 => ans = 24
I have solved the same problem in spoj platform, you just have to divide the value by 5 until the value becomes less than 5. print all the result of the division and that's your output.
To solve this problem, consider prime factorization of N factorial:
N! = 2^a1 * 3^a2 * 5^a3 * .... where a1, a2, a3, ... >= 0
Since N! = N*(N-1)(N-2)..., multiples of 2 are more frequent than 5.
So, a1 >= a3 in this expansion.
Number of trailing zeros = how many times you can divide N! by 10.
Which implies, ans = min(a1, a3) based on the prime factorization given above.
Since we already proved a1 >= a3, hence ans = a3, i.e power of 5 in the prime factorization of N!.
There will be floor(N/5) numbers that will contribute to power of 5 atleast once.
There will be floor(N/25) numbers that will contribute to power of 5 atleast twice.
There will be floor(N/125) numbers that will contribute atleast thrice
and so on.
The total power of 5 = floor(N/5) + floor(N/25) + floor(N/125) + ...
Implementation of this formula in code is left as an exercise.