Fibonacci sequence Pseudo-code Java - java

I'm trying to refresh my pseudo-code understanding and wanted to see what the correct way of writing out a Fibonacci number # n would be.
Given the code:
public class FibAtN{
public static void main(String args[]){
int j = 0;
int k = j;
int l = 1;
int n =; /*input*/
for(int i=0;i<n;i++){
j=k;
k=l;
l=j+k;
}
System.out.println(j);
}
}
Would the correct use of Pseudo-code be?
PROGRAM FibonnacciAtN
INITIALIZE four integers (say: j,k,l,n)
SET j equal zero, k equal j, l equal 1
SET n equal to INPUT
FOR (integer count is less than n, INCREMENT count every loop) DO
SET j=k, k=l, l=j+k
PRINT integer j
Thanks!

Related

Issue increment sum=0 by long integers pass 9 digits in Java

The program begins by asking the user to give a value assigned to variable n, the user will then be prompted to submit long digits n amounts of times. The digits will then be stored into the initialized array (ar). The function I am trying to create aVeryBigSum is to loop through the numbers in the array, incrementing sum=0 by the numbers in the array to provide the sum (Java).
For some reason however, the program works unless I use two consecutive numbers with greater than 9 digits.
For example:
aVeryBigSum(2,[111111111,111111111]) has n of 2 and two 9 digit numbers in the array
Output:
22222222
aVeryBigSum(2,[1111111111,1111111111]) has n of 2 and two 10 digit numbers in the array
Output:
-2072745074
Any idea what the issue might be? I've provided the program below:
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Main {
static long aVeryBigSum(int n, long[] ar) {
int sum = 0;
for (int i = 0; i < n; i++){
System.out.println(sum);
System.out.println(ar[i]);
sum += ar[i];
System.out.println(" ");
}
return sum;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
long[] ar = new long[n];
for(int ar_i = 0; ar_i < n; ar_i++){
ar[ar_i] = in.nextLong();
}
long result = aVeryBigSum(n, ar);
System.out.println(result);
}
}
Your problem is in the line
int sum = 0;
It should read
long sum = 0;
You are triggering integer overflow when the sum of integers exceeds 32 bits.
Yes, agree with Mad Physicist. You have to use long sum = 0. But to be the completely correct, you have possibility to have sum greater than Long.MAX_VALUE. You could use e.g. BigDecimal:
static BigDecimal aVeryBigSum(int n, long[] ar) {
BigDecimal sum = BigDecimal.ZERO;
for (int i = 0; i < n; i++) {
System.out.println(sum);
System.out.println(ar[i]);
sum = sum.add(new BigDecimal(ar[i]));
System.out.println(" ");
}
return sum;
}

nested for loops integers missing from array

Beginner here. I'm having problems running this series of for loops to find which integers are missing from an array.
public class FunWithArrays{
public static void main(String[] args){
String nString = args[0];
int n = Integer.parseInt(nString);
int inputArray [] = {1,2,4};
System.out.println(" The missing numbers are " );
findMissingNum(n, inputArray);
}
public static void findMissingNum(int n, int[] inputArray){
for (int i = 1; i <= inputArray.length; i++){
int count = 0;
for( int j = 0; j < n; j++){
if(inputArray[j] == i){
count ++;
}
if (count == 0){
System.out.println(i);
}
}
}
}
}
I get the answer I want, namely 3, however it doesn't print but rather shows up in a runtime error:
java.lang.ArrayIndexOutOfBoundsException: 3
at FunWithArrays.findMissingNum(FunWithArrays.java:17)
at FunWithArrays.main(FunWithArrays.java:9)
the method should take an input n from the user (when the program is run) as the largest value of the array and print all the ones missing
The logic is the outer for loop should traverse the array for numbers 1-n, and the inner loop should add to the count variable each time it finds a certain number. At the end of iteration it should print any numbers with a final "count" of 0. THIS IS LITERALLY DRIVING ME CRAZY!!! thanks in advance :)
First of all, you should traverse from 0 to (inputArray.length-1) index of inputArray. This will get rid of the ArrayIndexOutOfBoundsException, because java array indexing starts from 0 not 1.
And for inner loop, run from 0 to n, since n is the max number.
And Thirdly, it should be inputArray[i] == j, not inputArray[j] == i, same for printing the value. In you case I believe you have n>=4, so it was trying to access inputArray[3] via inputArray[j] call. That's why you are getting this out of bound error.
I think your code means like this: nest loop always run through inner loop first before run the outer loop.
public static void findMissingNum(int n, int[] inputArray){
for (int i = 1; i <= n; i++){
int count = 0;
for( int j = 0; j < inputArray.length; j++){
if(inputArray[j] == i){
count ++;
}
if (count == 0){
System.out.println(i);
}
}
}
}
I will just use a while loop instead:
int num =1;
while(num<=n){
for(int i = 0;i<inputArray.length;i++){
if(inputArray[i]!=num){
System.out.println(num);
}
}
num++;
}
The i incrementing to <= ipnutArray.length is not causing the error because i is never used as the index. What is causing the error is when n > length.
Also, you should not be checking n elements starting from the beginning because n is the max value, not the number of elements.

2D Array with variable internal array length JAVA

Im currently writing some code that print Pascal's Triangle. I need to use a 2D array for each row but don't know how to get the internal array to have a variable length, as it will also always changed based on what row it is int, for example:
public int[][] pascalTriangle(int n) {
int[][] array = new int[n + 1][]
}
As you can see I know how to get the outer array to have the size of Pascal's Triangle that I need, but I don't know how to get a variable length for the row that corresponds with the line it is currently on.
Also how would I print this 2D array?
Essentially what you want to happen is get the size of each row.
for(int i=0; i<array.size;i++){//this loops through the first part of array
for(int j=0;j<array[i].size;j++){//this loops through the now row
//do something
}
}
You should be able to use this example to also print the triangle now.
This is my first answer on StackOverFlow. I am a freshman and have just studied Java as part of my degree.
To make every step clear, I will put different codes in different methods.
Say n tells us how many rows that we are going to print for the triangle.
public static int[][] createPascalTriangle(int n){
//We first declare a 2D array, we know the number of rows
int[][] triangle = new int[n][];
//Then we specify each row with different lengths
for(int i = 0; i < n; i++){
triangle[i] = new int[i+1]; //Be careful with i+1 here.
}
//Finally we fill each row with numbers
for(int i = 0; i < n; i++){
for(int j = 0; j <= i; j++){
triangle[i][j] = calculateNumber(i, j);
}
}
return triangle;
}
//This method is used to calculate the number of the specific location
//in pascal triangle. For example, if i=0, j=0, we refer to the first row, first number.
public static int calculateNumber(int i, int j){
if(j==0){
return 1;
}
int numerator = computeFactorial(i);
int denominator = (computeFactorial(j)*computeFactorial(i-j));
int result = numerator/denominator;
return result;
}
//This method is used to calculate Factorial of a given integer.
public static int computeFactorial(int num){
int result = 1;
for(int i = 1; i <= num; i++){
result = result * i;
}
return result;
}
Finally, in the main method, we first create a pascalTriangle and then print it out using for loop:
public static void main(String[] args) {
int[][] pascalTriangle = createPascalTriangle(6);
for(int i = 0; i < pascalTriangle.length; i++){
for(int j = 0; j < pascalTriangle[i].length; j++){
System.out.print(pascalTriangle[i][j] + " ");
}
System.out.println();
}
}
This will give an output like this:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1

Java cut the sticks

I am very new to Java and I was trying to solve this problem on Hackerrank:
Here's the task:
https://www.hackerrank.com/challenges/cut-the-sticks
You are given N sticks, where the length of each stick is a positive
integer. A cut operation is performed on the sticks such that all of
them are reduced by the length of the smallest stick.
Suppose we have six sticks of the following lengths:
5 4 4 2 2 8
Then, in one cut operation we make a cut of length 2 from each of the six
sticks. For the next cut operation four sticks are left (of non-zero length), > whose lengths are the following:
3 2 2 6
The above step is repeated until no sticks are left.
Given the length of N sticks, print the number of sticks that are left before > each subsequent cut operations.
Note: For each cut operation, you have to recalcuate the length of smallest
sticks (excluding zero-length sticks).
Here is my attempt at it, but it doesnt seem to be working. The output gets stuck in while loop (4 gets printed out infinitely)
import java.io.*;
import java.util.*;
public class Solution {
private static int findMin (int[] A)
{
int min = A[0];
for (int i =0; i<A.length; i++)
{
if (A[i] < min)
{
min = A[i];
}
}
return min;
}
private static int countNonZeros (int[] A)
{
int zeros = 0;
for (int i =0; i<A.length; i++)
{
if (A[i] == 0)
{
zeros++;
}
}
int nonZeros = A.length - zeros;
return nonZeros;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int[] A = new int[n];
for (int i=0; i<n; i++)
{
A[i] = scanner.nextInt();
}
int nums = countNonZeros(A);
while (nums > 0)
{
int mins = findMin(A);
for (int j = 0; j<A.length; j++)
{
A[j]=A[j]-mins;
}
nums = countNonZeros(A);
System.out.println(nums);
}
}
}
Any help is appreciated
(PS I know I can just look the solution up somewhere, but I want to know why my code isn't working)
The problem that you have is that your findMin is not excluding zero-length elements, so once you have a zero that will be the min, and as a result an iteration of the while loop will be the same as the previous iteration, having subtracted 0 from each of the elements of A.

Analysis of execution frequency code

I was trying to find out the frequency of execution of some statements in the following code.
I wanted to check how many times each for loop was executed for a given input array.
For this purpose,I added three variables icnt,jcnt and kcnt.
public class FreqCounter{
public static void count1(int[] a){
int N = a.length;
int count = 0;
int icnt = 0;
int jcnt = 0;
int kcnt = 0;
for(int i=0;i<N;i++){
icnt++;
for(int j=i+1;j<N;j++){
jcnt++;
for(int k=j+1; k<N;k++){
kcnt++;
}
}
}
System.out.printf("i loop=%d times\n",icnt);
System.out.printf("j loop=%d times\n",jcnt);
System.out.printf("k loop=%d times\n",kcnt);
}
public static void main(String[] args) {
int N = 100;
int[] a = new int[N];
count1(a);
}
}
I got the following output
i loop=100 times
j loop=4950 times
k loop=161700 times
I tried to analyze this as follows
The outer for loop (i=0 to < N)
This executes N times ,so for N=100 ,the count will be 100
Inner for loop(j=i+1 to < N)
This is equivalent to finding combinations of N elements ,taken 2 at a time
which means C(N,2) = N! /((N-2)! * 2!) = (N *(N-1))/2 = ((N^2)/2)-(N/2)
For N=100 , this will be (100*100/2)-50 = 4950
Innermost loop (k=j+1 to < N)
Equivalent to finding combinations of N elements ,taken 3 at a time
ie, C(N,3) = N!/((N-3)! * 3!) = N*(N-1)*(N-2)/3! = (N^3/6)-(N^2/2)+N/3
For N=100, this will be 100^3/6 - 100^2/2 + 100/3 = 161700
I am getting the correct values,but wanted to know if the analysis(combinations stuff) is proper.(I have only recently learned the permutation/combinations lessons).If someone can add more to this analysis, it would be helpful.
Your combinatorics is perfectly fine, you have n distinct elements, and you need the number of possibilities to chose 3 elements, order does not matter, no repeats. This is indeed C(N,3).
(Disclaimer, I was a combinatorics TA during the last months)

Categories