Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with and , the first 10 terms will be:
1,1,2,3,5,8,13,21,34,...
And here we should find the even numbers in Fibonacci series and add them to the sum
And the code :
import java.util.*;
public class Abhi {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t = in.nextInt();
int[] n = new int[t];
int i,j;
long sum;
for(int a0 = 0; a0 < t; a0++){
n[a0] = in.nextInt();
}
//int an = n.length;
int[] nn = new int[1000];
nn[0]=1;
nn[1]=2;
for(i = 0 ; i<t;i++){
sum = 2;
for(j= 2;j<n[i];j++){
nn[j] = nn[j-2] + nn[j-1];
if(nn[j]%2==0 && nn[j]<n[i])
{
sum += nn[j];
//System.out.println(sum);
//the above line shows correct output
}
}
System.out.println(sum);//this is printing different output
}}}
Sample input :
1
100
Sample output :
44
Here problem in not with the outer System.out.println(sum); as you mentioned. It is because of int range.
Max value of int is 2 147 483 647 and in Fibonacci series 2 971 215 073 is in 47th position and as it exceeds the int range, it giving the results in unexpected manner.
In your code array nn holding -1323752223 instead of 2971215073 which is actually causing the issue.
To resolve this issue use BigInteger as below
BigInteger sum;
BigInteger[] nn = new BigInteger[1000];
nn[0] = new BigInteger("1");
nn[1] = new BigInteger("2");
for (i = 0; i < t; i++) {
sum = new BigInteger("2");
for (j = 2; j < n[i]; j++) {
nn[j] = nn[j - 2].add(nn[j - 1]);
if (nn[j].mod(new BigInteger("2")).equals(new BigInteger("0")) &&
nn[j].compareTo(new BigInteger(String.valueOf(n[i])))<0) {
sum = sum.add(nn[j]);
System.out.println(sum);
}
}
System.out.println(sum);
}
You can also achieve this by using below code:
import java.util.Scanner;
public class Fibo
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int No = sc.nextInt();
int fNo1 = 1;
int fNo2 = 1;
int fNo3 = fNo1 + fNo2;
int sumofEvenNo = 0;
int i;
while( fNo3 < No)
{
if(fNo3 % 2 == 0)
sumofEvenNo += fNo3;
fNo1 = fNo2;
fNo2 = fNo3;
fNo3 = fNo1 + fNo2;
}
System.out.println("Sum of all even nos = "+sumofEvenNo);
}
}
I suggest using naming convention, your code will be more clear and easy to debug. I'm using a static method to get the sum also.
Ask how many times the sum will be calculated.
Get the index and calculate the sum.
Print.
Class:
import java.util.*;
public class Abhi {
public static void main(String[] args) {
System.out.println ( "This program will calculate the even sum of given fibonacci series index ( index starts at 1) " );
System.out.println ( "Please enter how many times do you want to calculate the sum: " );
Scanner scan = new Scanner(System.in);
int iterationTimes = scan.nextInt() ;
for (; iterationTimes > 0; iterationTimes-- )
{
System.out.println ( "Please, enter the index on fibonacci: " );
System.out.println ( "Even sum: " + getEvenSum( scan.nextInt() ) );
}
}
private static long getEvenSum( int index)
{
if ( index <= 2 )
{
return 0;
}
long n1=1, n2=1, n3, sum = 0;
for(int i = 2; i < index; i++)
{
n3=n1+n2;
if ( n3 % 2 == 0)
{
sum += n3;
}
n1=n2;
n2=n3;
}
return sum;
}
}
I/O Example:
This program will calculate the even sum of given fibbonacci series index ( index starts at 1 )
Please enter how many times do you want to calculate the sum:
3
Please, enter the index on fibbonacci:
3
Even sum: 2
Please, enter the index on fibbonacci:
6
Even sum: 10
Please, enter the index on fibbonacci:
12
Even sum: 188
Note: Fibbonaci: 1, 1, 2, 3 ...
Related
I have a class assignment where we have to use Math.random to generate values of 0 or 1 representing heads and tails respectively. The point of the program is to have the user input the number of times the coin is flipped, and the program then spits out a string of random 0s and 1s representing the flips. The program then has to find and state the longest number of heads in a row.
eg.
(heads = 0 / tails = 1)
number of tosses: 10
result: 0001100100
longest sequence of heads: 3
this is what I have so far:
import java.util.Scanner;
import java.lang.Math;
public class CoinFlip
{
public static void main(String args[])
{
int Toss; // State variable for tosses
int Heads; // State variable for # of heads
System.out.println("Enter number of tosses:");
Scanner input1 = new Scanner(System.in);
Toss = input1.nextInt();
for(int i = 0; i < Toss ; i++)
{
int Coin = (int) (Math.random() + .5);
System.out.print(Coin); // Prints sequence of flips
}
System.out.println("");
System.out.println("Longest sequence of heads is "); // Says largest sequence of heads
}
}
I'm stuck as to how I read the sequence and then display the longest consecutive head count.
I have written a function to do this. I take the String that you were printing and made a String out of it. I pass this string as a parameter to the function and count the consecutive 0 in it.
This is the code for the same:
import java.util.Scanner;
public class CoinFlip {
public static void main(String args[]) {
int Toss; // State variable for tosses
System.out.println("Enter number of tosses:");
Scanner input1 = new Scanner(System.in);
Toss = input1.nextInt();
StringBuffer coinSequenceBuffer = new StringBuffer(Toss);
for (int i = 0; i < Toss; i++) {
int Coin = (int) (Math.random() + .5);
System.out.print(Coin); // Prints sequence of flips
coinSequenceBuffer.append(Coin);
}
String coinSequence = coinSequenceBuffer.toString();
System.out.println("");
int numberOfConsecutiveHead = findNumberOfConsecutiveHead(coinSequence);
System.out.println("Longest sequence of heads is " + numberOfConsecutiveHead);
}
private static int findNumberOfConsecutiveHead(String coinSequence) {
int count = 1;
int max = 0;
// Starting loop from 1 since we want to compare it with the char at index 0
for (int i = 1; i < coinSequence.length(); i++) {
if (coinSequence.charAt(i) == '1') {
// Since we are not intersted in counting 1's as per the question
continue;
}
if (coinSequence.charAt(i) == coinSequence.charAt(i - 1)) {
count++;
} else {
if (count > max) { // Record current run length, is it the maximum?
max = count;
}
count = 1; // Reset the count
}
}
if (count > max) {
max = count;
}
return max;
}
}
I have tried adding comments so that you can easily understand it. Let me know if you face any issue in understanding it.
This is pretty simple. Just count zeros and reset counter when not zero.
public static void main(String... args) {
System.out.print("Enter number of tosses: ");
int[] arr = new int[new Scanner(System.in).nextInt()];
Random random = new Random();
for (int i = 0; i < arr.length; i++)
arr[i] = random.nextInt(2);
System.out.println(Arrays.toString(arr));
System.out.println("Longest sequence of heads is " + findLongestZeroSequence(arr));
}
public static int findLongestZeroSequence(int... arr) {
int res = 0;
for (int i = 0, cur = 0; i < arr.length; i++) {
if (arr[i] == 0)
res = Math.max(res, ++cur);
else
cur = 0;
}
return res;
}
Here's my go at it:
class CoinFlip {
public static void main(String args[])
{
// Get number of tosses from user
System.out.print("Enter number of tosses: ");
System.out.flush();
Scanner input1 = new Scanner(System.in);
int toss = input1.nextInt();
// Build a string of random '0's and '1's of the specified length (number of tosses)
StringBuilder sb = new StringBuilder();
for(int i = 0; i < toss ; i++)
{
long coin = Math.round(Math.random());
sb.append(coin == 0? '0' : '1');
}
String seq = sb.toString();
// Print the generated String
System.out.println(seq);
// Walk through the string tallying up runs of heads
int count = 0;
int max = 0;
for (int i = 0 ; i < seq.length() ; i++) {
if (seq.charAt(i) == '0') {
count += 1;
} else {
if (count > max)
max = count;
count = 0;
}
}
// Gotta check at the end to see if the longest sequence of heads
// was at the end of the string
if (count > max)
max = count;
// Print the length of the longest sequence
System.out.println("Longest sequence of heads is " + max);
}
}
Sample run:
Enter number of tosses: 40
1000001000000010010101011000011100001000
Longest sequence of heads is 7
Explanations after the code.
import java.util.Scanner;
public class CoinFlip {
private static final int HEADS = 0;
private static final int TAILS = 1;
public static void main(String[] args) {
Scanner input1 = new Scanner(System.in);
System.out.print("Enter number of tosses: ");
int toss = input1.nextInt();
int count = 0;
int longest = 0;
StringBuilder sb = new StringBuilder(toss);
for (int i = 0; i < toss; i++) {
int coin = (int) ((Math.random() * 10) % 2);
sb.append(coin);
System.out.printf("Got %d [%s]%n", coin, (coin == HEADS ? "HEADS" : "TAILS"));
if (coin == HEADS) {
count++;
System.out.println("count = " + count);
}
else {
if (count > longest) {
longest = count;
System.out.println("longest = " + longest);
}
count = 0;
}
}
if (count > longest) {
longest = count;
System.out.println("longest = " + longest);
}
System.out.println(sb);
System.out.print("Longest sequence of heads is " + longest);
}
}
In order to generate a random number which must be either 0 (zero) or 1 (one), I call method random() of class java.lang.Math. The method returns a double between 0.0 and 1.0. Multiplying by ten and then performing modulo 2 operation on that number returns either 0.0 or 1.0 which is a double and therefore needs to be cast to an int.
Each time the above calculation returns 0 (zero) I increment a count. If the calculation returns 1 (one) then I check whether the count is greater than longest and update longest accordingly, after which I reset the count back to zero.
Note that if the last toss is "heads" then the check for the longest sequence will not be performed. Hence I repeat the check for the longest sequence after the for loop.
At the end of the for loop, I have all the required information, i.e. the string that records all the results of all the coin tosses plus the longest sequence of heads.
Here is sample output:
Enter number of tosses: 10
Got 1 [TAILS]
Got 1 [TAILS]
Got 1 [TAILS]
Got 0 [HEADS]
count = 1
Got 1 [TAILS]
longest = 1
Got 0 [HEADS]
count = 1
Got 0 [HEADS]
count = 2
Got 1 [TAILS]
longest = 2
Got 0 [HEADS]
count = 1
Got 0 [HEADS]
count = 2
1110100100
Longest sequence of heads is 2
num = Integer.parseInt(tf1.getText());
entered = Integer.parseInt(tf1.getText());
num2 = Integer.parseInt(tf2.getText());
entered2 = Integer.parseInt(tf2.getText());
for (i =(int) num; i<= num2 ; i++){
for (j=0 ; j >= i ; j++) {}
System.out.println(i);
}
do i have to use array list ? ArrayList<Integer> lists = new ArrayList<Integer>();
and if i use it how i can to separate each number in the arraylist,so I found the numbers between two numbers but how I can take each number and do the collatz conjecture java , please i need help quickly
The collatz conjecture is simple n = n/2 if n%2 == 0 and n = 3*n + 1 if n%2 == 1 and you're doing these calculations until n = 1. Based on this, you could write your function like this:
public static List<Integer> calculateConjecture(int number) {
List<Integer> values = new ArrayList<>();
while (number != 1) {
if (number % 2 == 0) {
number = number / 2;
} else {
number = 3 * number + 1;
}
values.add(number);
}
return values;
}
public static void main(String[] args) {
int inferiorLimit = 11;
int superiorLimit = 15;
for (int i = inferiorLimit; i <= superiorLimit; i++) {
System.out.println(calculateConjecture(i));
}
}
The values ArrayList will hold the sequence of numbers for the current number between the [inferiorLimit,superiorLimit]
Have some loops homework to do, and need some help! Here are the 3 questions:
Us the method below to take two integers and only output numbers divisible by ten. Make the list start with the largest of the numbers.
public static void divisibleByTen( int start, int end )
The above method is the example on the HW sheet. I have no idea how to implement it. I also don't know how to start with the largest number. Right now, I don't know how to take user input into the loop, so I made an example with 10 and 100:
public class QuestionOne {
public static void main(String [] args) {
for (int i = 10; i <= 100; i += 10){
System.out.println(i + "");
}
}
}
Use the method below to output the triangle below. Assume the positive number is between 3 and 9.
public static void printLeftUpper( int num)
Desired output is this number triangle:
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
Here's my code so far:
public class QuestionTwo {
public static void main(String [] args) {
for(int i = 5; i >= 1; i--) {
for(int j = 1; j <= i; ++j) {
System.out.print(j + " ");
}
System.out.println();
}
}
}
The third question I have ZERO idea how to start.
3. public static void sumEvens( int begin, int end )
Use the method above to take in two numbers, called begin and end, inclusive, checks if the numbers between them are even. Include the numbers in the sum if they are even as well, and print out the sum of all such numbers.
Example: sumEven(16, 11) uses 16+14+12 = 42, and outputs "For numbers between 16 and 11, the sum of all even numbers is 42."
The help is GREATLY appreciated. Thanks so much!!
Who likes homework? I've taken the liberty of doing Question 3, hope that helps!
import java.util.List;
import java.util.ArrayList;
public class OddEven {
public static void main(String[] args) {
sumEvens(0,1000);
}
// Gets sum of odd and even numbers between a given range:
public static void sumEvens(int begin, int end)
{
List<Integer> evenNumbers = new ArrayList<Integer>();
List<Integer> oddNumbers = new ArrayList<Integer>();
if (begin < end)
{
for (int i = begin; i <= end; i++)
{
// Number is even:
if (i % 2 == 0)
{
evenNumbers.add(i);
}
// Number is odd:
else
{
oddNumbers.add(i);
}
}
}
else
{
for (int i = begin; i >= end; i--)
{
// Number is even:
if (i % 2 == 0)
{
evenNumbers.add(i);
}
// Number is odd:
else
{
oddNumbers.add(i);
}
}
}
// Calculate even values:
int evenSum = 0;
for (int i: evenNumbers) {
evenSum += i;
}
System.out.println("The sum of all even numbers is: " + evenSum);
// Calculate odd values:
int oddSum = 0;
for (int i: oddNumbers) {
oddSum += i;
}
System.out.println("The sum of all odd numbers is: " + oddSum);
}
}
public class QuestionOne {
public static void main(String [] args) {
divisibleByTen( 1, 100 );
}
public static void divisibleByTen( int start, int end ){
// reversal big to small (100 to 1)
for(int i = end; i >= start; i--){
// use mod (%) to check if i is divisible by 10
if( i%10 == 0 ){
// it is then output
System.out.println(i);
}
}
}
}
Question 2 is correct.
Question 3
public static void main(String [] args) {
sumEvens( 16, 10);
}
public static void sumEvens( int begin, int end ){
int start = 0;
int last = end;
int sum = 0;
if(begin > end){
start = end;
end = begin;
}else{
start = begin;
}
for(int i = start; i <= end; i++){
// get even integers
if(i%2 == 0){
sum += i;
}
}
System.out.println("For numbers between " +begin+ " and " +last+ ", the sum of all even numbers is " +sum);
}
Following code tries to compute the nCr values for the various values of given n and here r varies from 0 to n.
The input is in the following format :-
Input Format
The first line contains the number of test cases T.
T lines follow each containing an integer n.
Constraints
1<=T<=200
1<=n< 1000
Output Format
For each n output the list of nC0 to nCn each separated by a single space in a new line. If the number is large, print only the last 9 digits. i.e. modulo 10^9
So Sample Input is of the follwing format :-
3
2
4
5
And the sample output is of the follwing format :-
1 2 1
1 4 6 4 1
1 5 10 10 5 1
Here is the code
import java.io.*;
import java.util.*;
import java.math.*;
public class Solution {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int j = 0;
for(int i = 0; i < n; i++){
int a = scan.nextInt();
j = 0;
while(j <= a){
if( j == 0 || j == a){
System.out.print(1 + " ");
}
else if( j == 1 || j == (a - 1)){
System.out.print(a + " ");
}else{
BigInteger a1 = (Num(a,j));
BigInteger b1 = BigInteger.valueOf(fact(j));
BigInteger c1 = a1.divide(b1);
BigInteger x1 = BigInteger.valueOf(1000000000);
System.out.print( c1.mod(x1) +" ");
}
j++;
}
System.out.println();
}
}
public static BigInteger Num(int a, int j){
BigInteger prod = BigInteger.valueOf(1);
for(int k = 0; k < j; k++){
int z = a - k;
BigInteger b = BigInteger.valueOf(z);
prod = prod.multiply(b);
}
return prod;
}
public static long fact(long j){
long prod = 1;
for(long i = j; i > 0; i--){
prod *= i;
}
return prod;
}
}
Its clearing some test cases but its failing in many of them.
Saying Run Time Error, when I tested it on my input of 1 999 it threw Arithmetic Exception "Divide by zero".
Here is the exception log :-
Exception in thread "main" java.lang.ArithmeticException: BigInteger divide by zero
at java.math.MutableBigInteger.divideKnuth(MutableBigInteger.java:1179)
at java.math.BigInteger.divideKnuth(BigInteger.java:2049)
at java.math.BigInteger.divide(BigInteger.java:2030)
at Solution.main(Solution.java:25)
What needs to be done to fix this?
You must use BigInteger for the computation of factorials up to around 1000.
public static BigInteger fact(long j){
BigInteger prod = BigInteger.ONE;
for(long i = j; i > 0; i--){
BigInteger f = BigInteger.valueOf( i );
prod = prod.multiply( f );
}
return prod;
}
After thinking about for 1 hour I am still not able to figure out whats the problem with my calculator. I have made 3 function which include main(), calculateBinomialTheorem() and factorial(). Yes, factorial() to calculate the coefficient.
public static void main(String[] args) {
Scanner a_input = new Scanner(System.in);
Scanner b_input = new Scanner(System.in);
Scanner n_input = new Scanner(System.in);
int a = 0;
int b = 0;
int n = 0;
System.out.println("Welcome to Binomial Theorem Solver:");
System.out.print("a: ");
a = a_input.nextInt();
System.out.print("b: ");
b = b_input.nextInt();
System.out.print("n: ");
n = n_input.nextInt();
System.out.print(calculateBinomialTheorem(a, b, n));
a_input.close();
b_input.close();
n_input.close();
}
private static int calculateBinomialTheorem(int a, int b, int n) {
int result = 0;
int coefficient = 0;
ArrayList<Integer> products = new ArrayList<Integer>();
for(int i = 1; i <= n; i++) {
int product = 0;
coefficient = factorial(n) / (factorial(i) * factorial(n - i));
product = (int) (coefficient*Math.pow(a, n - i)*Math.pow(b, i));
products.add(product);
}
for(int c : products) {
result += c;
}
return result;
}
private static int factorial(int num) {
int factorial = 1;
if(num > 0) {
for ( int c = 1 ; c <= num ; c++ )
factorial = factorial*c;
} else {
return 0;
}
return factorial;
}
I tried to run it with the values of 3, 3, 3 that should give me the answer of 216 but its not giving! Why? Every time I run it with those values this is the error that I get:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at binomial_thorem_solver.Main.calculateBinomialTheorem(Main.java:46)
at binomial_thorem_solver.Main.main(Main.java:29)
I know that I am dividing the number by 0 but I am not getting how to resolve that issue.
Please help.
UPDATE: Thanks for the answers. You all figured out what the problem was but then there was another problem aswell that the loop was iterating one less time because i waas initially set to 1. I set that to 0 and it worked!
The problem is in your factorial method.. for 0 your factorial will return 0..
and you are dividing the value with the result of factorial (i.e. 0).. the factorial of 0 is 1. so your code should be
private static int factorial(int num) {
int factorial = 1;
if(num > 0) {
for ( int c = 1 ; c <= num ; c++ )
factorial = factorial*c;
} else {
return 1;
}
return factorial;
}
In the first iteration, i = 1, you have:
coefficient = factorial(n) / (factorial(i) * factorial(n - i));
What is factorial(1)? It's 1 according to your code.
What is dactorial(0)? It's 0 according to your code (if(num > 0) is false, so you go to else - there you return 0).
So, as the exception is telling you, you are trying to divide by zero.
How to fix this?
0! is defined to be 1. So you should check this special case and return 1 if the number is 0.
0! = 1 by convention. Not 0. This might cause problem to you.
Moreover, for loop should go from 0 to n, not from 1 to n as there are n+1 terms.
You are missing C(n,0)*a^0*b^n part as your iteration is not going from 0 to n.
So, your loop should be
for(int i = 0; i <= n; i++) {
int product = 0;
coefficient = factorial(n) / (factorial(i) * factorial(n - i));
product = (int) (coefficient*Math.pow(a, n - i)*Math.pow(b, i));
products.add(product);
}
In your case, since C(3,0)*3^0*3^3 that is 27 is missing from the final product. That is why you are getting 216 - 27 = 189.
You need to return 1 from the factorial functiom if num is zero.
factorial 0 equals 1.
if(num > 0) {
for ( int c = 1 ; c <= num ; c++ )
factorial = factorial*c;
} else {
return 1;
}