Fibonacci sequence has a negative number [duplicate] - java

This question already has answers here:
Often big numbers become negative
(4 answers)
Closed 2 years ago.
I have this code for fibonacci sequence :
public class Fibonacci {
private List<Integer> fibonacci;
public void fillFibonacci(){
fibonacci = new ArrayList<>();
int n1 = 1 , n2 = 1 , n3;
fibonacci.add(n1);
fibonacci.add(n2);
for(int i = 2 ; i < 4000 ; i ++){
n3 = n1 + n2;
fibonacci.add(n3);
n1=n2;
n2=n3;
}
}
public void printFibonacci(){
for(int i = 0 ; i < fibonacci.size() ; i ++){
System.out.print(fibonacci.get(i) + " ");
System.out.println(i);
}
}
}
this code show negative number what's wrong with it?

You cannot go up to index= 4000 in this loop, you have integer overflowed. Maximum you can go to is 49. Change the loop as such.
for(int i = 2 ; i < 49 ; i ++){
n3 = n1 + n2;
fibonacci.add(n3);
n1=n2;
n2=n3;
}

The 4000-th Fibonacci number has 836 digits. The java int type has 32-bits and can fit numbers up to 10 digits. After that it overflows and may go negative. If you want big numbers, change your code to use BigInteger.

Related

The sum of all odd digits of an input [duplicate]

This question already has answers here:
How do I find the sum of all odd digits of user input numeric string?
(5 answers)
Closed 2 years ago.
How to compute the sum of all 'odd digits of an input' using 'loop'. (For example, if the input is 32677, the sum would be 3 + 7 + 7 = 17.)
I can't quite figure out how to do that, can someone please help me out. This is what I have done so far, I don't know how to complete it or whether I have its right or wrong.
Any help would be appreciated!
System.out.println("Enter a number: ");
String input = in.nextLine();
int length = input.length();
int sum = 0;
int digits = 0;
for (int i = 0; i < length; i++) {
if (length % 2 == 1) {
digits += i;
sum = digits++;
}
}
System.out.println(sum);
Here comes a Java8-based solution:
final int result = input.chars()//make a stream of chars from string
.mapToObj(String::valueOf) // make every character a String to be able to use parseInt later
.mapToInt(Integer::parseInt) // transform character in int
.filter(i -> i % 2 == 1) // filter out even numbers
.sum();
You don't need to use String if your input is not so long.
also for safe side use long datatype.
Here is the working code with comments (explain each step).
long sumOddDigits(long value){
long temp = value; // copy in temp variable
long sum = 0;
while(temp > 0){
int digit = temp%10; // get last digit of number. example: 227 gives 7.
temp = temp / 10; // remove that last digit from number.227 will be 22.
if(digit % 2 == 1){
sum += digit;
}
}
return sum;
}
Your interpretation of the digits inside of input is not working this way.
System.out.println("Enter a number: ");
String input = in.nextLine();
int length = input.length();
int sum = 0;
for (int i = 0; i < length; i++) {
int digit = input.charAt(i) - '0';
if (digit % 2 == 1) {
System.out.println("Add digit: " + digit);
sum += digit;
}
}
System.out.println(sum);
In your loop, use Integer.parseInt(input.charAt(i)) to get the number at position i.
if(length%2==1){ that doesn't make sense here. You want to check if your number is odd, not the length of your string.

Question about adding three digits with each other in java [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I have a task to add each numbers. One of my colleague helped me out and here's the code.
public class Solution {
public static void main(String[] args) {
System.out.println(sumDigitsInNumber(546));
}
public static int sumDigitsInNumber(int number) {
int sum = 0;
sum = sum + number%10;
number = number/10;
sum = sum + number%10;
number = number/10;
sum = sum + number%10;
number = number/10;
return sum;//write your code here
}
I'm not sure exactly how this works. Can someone please explain to me? Thanks.
You can use within while the loop which will accept any number as #GBlodgett suggested
public static void main(String[] args) {
System.out.println(sumDigitsInNumber(546));
}
public static int sumDigitsInNumber(int number) {
int sum = 0;
while(number!=0)
{
sum = sum + number%10;
number = number/10;
}
return sum;//write your code here
}
In Java % is the modulo operator. It delivers the remainder of that division. If you divide integer values in Java, any remainder will be lost.
If you add some makeshift logging like that:
public static int sumDigitsInNumber(int number) {
int sum = 0;
sum = sum + number % 10;
number = number / 10;
System.out.println(number);
sum = sum + number % 10;
number = number / 10;
System.out.println(number);
sum = sum + number % 10;
number = number / 10;
System.out.println(number);
return sum; // write your code here
you will get the following output:
54
5
0
15
546 % 10 = 6
546 / 10 = 54
54 % 10 = 4
54 / 10 = 5
5 % 10 = 5
5 / 10 = 0
sum = 6 + 5 + 4 = 15
Your code will only work up to three digits. If you transfer the sequence of modulo and division operations into a loop it will be a generic solution.
The JVM(Java Virtual Machine) starts executing your code and public static void
main(String[] args) is the starting point.
Then executes System.out.println(sumDigitsInNumber(546));
System.out.println() is a method that prints the argument passed, into the System.out which is generally stdout (Standard output). The argument passed is the sumDigitsInNumber(546) method, hence it would print what sumDigitsInNumber() would return.
sumDigitsInNumber() initializes a sum variable with 0 to store the sum of 546.
sum = sum + number%10 gives you 6 (0 + 6), where number%10 gives
the last digit of 546 which is 6
number = number / 10 will replace number by 54 because 546/10 is 54.6 since it is an integer division .6 is ignored and 54 is stored in the number.
Repeat the above step twice but the number being 54 and then 5.
return sum returns the sum to the caller which is your main() method, hence System.out.println() printing the sum of 546.
Step by step:
this creates variable named sum and assigns it value of 0:
int sum = 0;
this does the following:
it assigns to variable 'sum' the result of sum + number % 10 (where a number is an argument passed to the method)
sum = sum + number%10;
number % 10 is in your example a remainder of 456 / 10, so in 456, you can pack number 10 exactly 45 times, whatever is left that is less then 10 is your result (remainder), in this case 6.
see http://www.cafeaulait.org/course/week2/15.html
next we divide current number by 10:
number = number / 10;
so 456 / 10 = 45.6
and as the type of variable is int - it is actually 45 (as int always rounds down the remainder) - see Int division: Why is the result of 1/3 == 0?
then it is being repeated 2 times until all 3 digits are summed up.
Notice, that your method will only work for 3 digit numbers. That's not that good.
You can easily make your method to work with any digits length int number passed.
Hint: use loops!
As you can see, you're repeating the same piece of code 3 times.
You could place it inside a loop and make it execute as many times as there are digits in your number.
something along these lines, but you need to figure out when to stop the while loop!
int sum = 0;
while (?WHEN TO EXIT?) {
sum = sum + number % 10;
number = number / 10;
}
Think about when you can exit loop (when, in example, maybe this number variable that you divide by 10 each iteration can tell you that all digits have been processed?)
Here is a solution that computes the sum of a number, no matter how many digits it has:
Generally speaking, a number has exactly [log(number)+1] digits, the tempInt variable is introduced to store the parameter value, it is considered a bad practice to modify the values of the method parameters :
public static int sumOfDigits(int number) {
int sum = 0;
int length = (int) Math.ceil(Math.log10(number));
int tempInt = number;
for (int i = 0; i < length; i++) {
sum += tempInt % 10;
tempInt /= 10;
}
return sum;
}
public class Solution {
public static void main(String[] args) {
System.out.println(sumDigitsInNumber(546));
}
public static int sumDigitsInNumber(int number) {
int sum = 0;
sum = sum + number%10; // number%10 = the last digit of 546 (= 6), sum = 0 + 6
number = number/10; // number = number whithout the last digit (54)
sum = sum + number%10; // number%10 = the last digit of 54 (= 4), sum = 0 + 6 + 4
number = number/10; // number = number whithout the last digit (5)
sum = sum + number%10; // number%10= the last digit of 5 (= 5), sum = 0 + 6 + 4 + 5
number = number/10; // number = number whithout the last digit (useless)
return sum;//sum = 6 + 5 + 4 = 15
}

Displaying 500 random integers [duplicate]

This question already has answers here:
How do I generate random integers within a specific range in Java?
(72 answers)
Closed 4 years ago.
I want to generate 500 random numbers and display them next to their indexes. I want the numbers to be 1 though 10. But when I run my code it only generates 13 random numbers and the numbers are greater than 10. Please help.
public class RandomStats {
public static void main(String[] args) {
int [] stats = new int [501];
int numRolls;
int outcome;
for (int i = 0; i <=500; i++ ){
outcome = (int) ( 10 * Math.random() + 1)
+ (int) ( 10 * Math.random () + 1);
stats[outcome] += 1;
}
for ( int i = 2; i <=500; i++) {
System.out.println(i + ": " + stats[i]);
}
}
}
While saving in the array, you are doing stats[outcome] += 1;, where your array is updated with same index again and again and thats the reason you only see ~13 values and rest as 0. I believe it should be stats[i] =outcome+ 1;

ADACON : Ada and connections SPOJ(TLE)

This is a problem from SPOJ. I am getting TLE. Need help to improve its time complexity. There is one test-case that i know will fail. But I will take care of it after the time complexity is reduced.
Ada the Ladybug was on a trip with her friends. They each bought a souvenir there. As all of them are mathematicians, everybody bought a number. They want to modify the numbers to have some connection between each other. They have decided to modify the numbers sou they would have their GCD greater than 1 ( gcd(a1,a2,a3,...,aN) > 1). Anyway it is not easy to change a number - the only thing they can do is to go to a proffesor in mathematics, which could forge a number A into number A+1 or A-1. As this operation is not cheap, they want to minimize number of such operations. A number might be forged any number of times.
NOTE: gcd(a,0)==a (so gcd of two 0 is also 0)
Input
The first line contains an integer 1 ≤ N ≤ 3*10^5, the number of friend who were on trip (and also the number of numbers).
The second line contains N integers 0 ≤ a_i ≤ 10^6
Output
Print a single line with minimum number of operations to make a connection between all numbers.
Example Input
5
3 9 7 6 31
Example Output
2
Example Input 2
9
3 4 5 7 8 9 11 12 13
Example Output 2
6
Example Input 3
5
7 7 11 17 1
Example Output 3
5
APPROACH
First i find the primes upto (largest/2 + 1) element in the given array of numbers(using function findPrimes()). And then for every element in the array, find how many operations are going to be needed for each of the primes to be its divisor. The smallest summation for each prime, I am printing as solution.
CODE
import java.io.*;
public class Main
{
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int largest = Integer.MIN_VALUE;
int n = Integer.parseInt(br.readLine());
int[] arr = new int[n];
String[] strArr = br.readLine().split(" ");
for(int i = 0 ; i < n ; i++)
{
arr[i] = Integer.parseInt(strArr[i]);
if(arr[i] > largest)
{
largest = arr[i];
}
}
func(n,arr,largest);
}
public static void func(int n,int[] arr,int largest)
{
int[] primes = findPrimes(largest / 2 + 1);
//int[] primes = findPrimes((int)Math.sqrt(largest));
int lenOfPrimes = primes.length;
int[] mat = new int[lenOfPrimes];
for(int j = 0 ; j < lenOfPrimes ; j++)
{
if(arr[0] < primes[j])
{
mat[j] = primes[j] - arr[0];
}
else if(arr[0] % primes[j] == 0)
{
mat[j] = 0;
}
else
{
int rem = arr[0] % primes[j];
mat[j] = Math.min(rem,primes[j] - rem);
}
}
for(int i = 1 ; i < n ; i++)
{
for(int j = 0 ; j < lenOfPrimes ; j++)
{
if(arr[i] < primes[j])
{
mat[j] = mat[j] + primes[j] - arr[i];
}
else if(arr[i] % primes[j] == 0)
{
mat[j] = mat[j] + 0;
}
else
{
int rem = arr[i] % primes[j];
mat[j] += Math.min(rem,primes[j] - rem);
}
}
}
int smallest = Integer.MAX_VALUE;
for(int i = 0 ; i < lenOfPrimes ;i++)
{
if(mat[i] < smallest)
smallest = mat[i];
}
System.out.println(smallest);
}
public static int[] findPrimes(int upto)
{
boolean[] primes = new boolean[upto + 1];
for(int i = 0 ; i < upto + 1 ; i++)
primes[i] = true;
int count = 0;
primes[0] = primes[1] = false;
int limit = (int)Math.sqrt(upto + 1);
for(int i = 2 ; i < upto + 1; i++)
{
if(primes[i] == true)
{
count++;
if(i <= limit)
{
for(int j = i * i ; j < upto + 1 ; j += 2 * i)
{
primes[j] = false;
}
}
}
}
int[] primeContainer = new int[count];
int index = 0;
for(int i = 2 ; i < upto + 1 ; i++)
{
if(primes[i] == true)
{
primeContainer[index++] = i;
if(index == count)
break;
}
}
return primeContainer;
}
}
The solution that you are trying will give you correct answer. But since there are many prime numbers till 1000000, (~ 78000) hence 78000*300000 will definately give you TLE.
Try to think in terms of sieve. The sieve of eratosthenes works in O(nlogn) time.
Now you would have already figured out that you would change numbers such that it is divisible by some prime number. (As in your algorithm you are considering only prime numbers). So now lets take a prime number say 7. Now you need to find number of transformation of numbers from 0 to 3, because you need to change these numbers to 0. Similarly you need to find number of numbers from 4 to 10 as you will change them to 7 to get them divisible by 7 considering minimum operations. Similarly you would do the same to numbers from 11 to 17, changing them to 14, and so on for rest of the numbers till 1000000. You need to do the same for all prime numbers. This can be achieved using sieve.
The number of operations in this case will be n/2 + n/3 + n/5 + n/7 + n/11 + .... ~ nlogn.
You can read more about sieve from here: https://www.geeksforgeeks.org/sieve-of-eratosthenes/
May be its too late but let me answer this.
I was able to sole this problem using below approach.
My Java Solution take 3.8 S on SPOJ for all 15 test cases combine.
1.Find prime divisors of n in O(log n)
Source https://www.geeksforgeeks.org/prime-factorization-using-sieve-olog-n-multiple-queries/
2. While computing factorization store prime divisors in array let say UniquePrimeWhicheDividsAtleastOneNumber[]
here is a catch always keep 2 in this UniquePrimeWhicheDividsAtleastOneNumber if its not available.
UniquePrimeWhicheDividsAtleastOneNumber[0]=2
3. now you can loop through these primes and find the sum of smallest reminders by these primes.
long minTemp = 0, minAns = Long.MAX_VALUE;
for (int i = 0; i < UniquePrimeWhicheDividsAtleastOneNumber.length; i++) {
for (int j = 0; j < n; j++) {
int rem = InputNumbers[j] % UniquePrimeWhicheDividsAtleastOneNumber[i];
minTemp += Math.min(rem, UniquePrimeWhicheDividsAtleastOneNumber[i] - rem);
if (minTemp > minAns)
break;// no need to compute sum of reminders if it exceeded the current minimum.
}
minAns = Math.min(minAns, minTemp);
minTemp = 0;
}
minAns --> is your answer.

generate random numbers with no zero [duplicate]

This question already has answers here:
How do I generate random integers within a specific range in Java?
(72 answers)
Closed 5 years ago.
How do I get random number in the range st 1 to 45 only (not included zero). Here is my code so far:
int number;
Random randomNum = new Random();
number = randomNum.nextInt(45)+1;
for (int y = 0; y < 10; y++) {
System.out.println("");
for (int i = 1; i <=6; i++) {
number= randomNum.nextInt(45);
if (i==6) {
System.out.printf("%d",number);
}
else {
System.out.printf("%d-",number);
}
}
}
randomNum.nextInt(45) + 1 will generate a number from 0 to 44 and add 1, thus generating numbers from 1 to 45.

Categories

Resources