How can I print the value of a Fibonacci function for any particular index, say n, where n is the provided argument value?
1 import java.util.Arrays;
2
3 public class Fibonacci {
4
5 public static void main(String[] args) {
6 int n = Integer.parseInt(args[0]);
7 if(n<3){
8 return;
9 }else{
10 int[] f = new int[n];
11 f[0] = 1;
12 f[1] = 1;
13 int i= 0;
14 for(i=2; i<f.length; i++){
15 f[i]= f[i-1]+ f[i-2];
16 }
17 System.out.println(f[i]);
18 }
19
20 }
21
22 }
Your code is basically fine, but I tweaked a few things in my response:
public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
if (n < 0) {
System.out.println("Cannot computer Fib() of a negative number.");
return(0);
} else if (n < 3) {
System.out.println("Fib[" + n + "] = 1");
} else {
int[] f = new int[n];
f[0] = 1;
f[1] = 1;
for(int i=2; i < f.length; ++i) {
f[i] = f[i-1]+ f[i-2];
}
System.out.println("Fib[" + n + "] = " + f[n - 1]);
}
}
The problem you have, I believe, is System.out.println(f[i]);
At this spot, i will be equals to length of f[]. If you use i as index, it will be out of bound.
If you are going to print the last value, it should be System.out.println(f[i-1]);
You are printing f[i] which will give you ArrayIndexOutOfBoundsException since at that time value of i crosses the boundary of array f.
A simple workaround would be to print array by taking a separate variable like this :
int n = Integer.parseInt(args[0]);
if(n<3){
return;
}else{
int[] f = new int[n];
f[0] = 1;
f[1] = 1;
int i= 0;
for(i=2; i<f.length; i++){
f[i]= f[i-1]+ f[i-2];
}
for (int j=0;j<n;j++){
System.out.println(f[j]);
}
}
If you want to print any particular index then you can make one boundary check before printing:
int index=5;
if(index<f.length){
System.out.println(f[index]);
}
I think It's better to have Fibonachi in the recursive way:
public int fib(int n) {
if (n < 2) {
return n;
}
else {
return fib(n-1)+fib(n-2);
}
System.out.println(n);
}
Related
This is an exercise.
A perfect number is a number whose sum of divisors without itself is equal to that number
6 is a perfect number because its divisors are: 1,2,3,6 and 1 + 2 + 3 = 6
28 is a perfect number because its divisors are: 1,2,4,7,28 and 1 + 2 + 4 + 7 = 28
Task: write the body of findNPerfectNumbers, which will find n prime perfect numbers and return them as a list
I must use this program:
import java.util.ArrayList;
public class Exercise {
public static ArrayList<Integer> findNPerfectNumbers(int n)
{
return new ArrayList<>();
}
public static void main(String[] args)
{
System.out.println(findNPerfectNumbers(4));
}
}
I create this code to resolve this problem, but I have a problem to return an ArrayList. I don't know how. It should look like this example: 6 = 1,2,3,6 ///// 28 = 1, 2, 4, 7
My idea:
import java.util.ArrayList;
public class Main
{
public static ArrayList<Integer> findNPerfectNumbers(int n)
{
int sum = 0;
ArrayList<Integer> perfectList = new ArrayList<>();
ArrayList<Integer> factorList = new ArrayList<>();
for (int i = 6; i < n; i++)
{
factorList.clear();
for (int j = 1; j <= i / 2; j++)
{
if (i % j == 0)
{
factorList.add(j);
}
}
sum = 0;
for (int h = 0; h < factorList.size(); h++)
{
sum = sum + factorList.get(h);
}
if (sum == i)
{
perfectList.add(i);
}
}
return perfectList;
}
public static void main(String[] args)
{
System.out.println(findNPerfectNumbers(28));
}
}
Anyone have an idea?
The question is as simple as to have the findNPerfectNumbers function return the first N perfect numbers.
The main part for the exercise is probably to do this as efficiently as possible. For example limiting divider check by half like you do in for (int j = 1; j <= i / 2; j++) is one of many options.
The reason your function doesn't return anything though is because your outer for loop is incorrect with the given input of 4 what you'r doing is for (int i = 6; i < 4; i++) which doesn't do any loops because 4 is smaller than 6.
what you probably intended to do issomething like for (int i = 6; perfectList.size() < n; i++) which would loop aslong as you have fewer than N perfect numbers.
example working code:
import java.util.ArrayList;
public class Exercise {
public static ArrayList<Integer> findNPerfectNumbers(int n) {
int sum = 0;
ArrayList<Integer> perfectList = new ArrayList<>();
for (int i = 6; perfectList.size() < n; i++) {
ArrayList<Integer> factorList = new ArrayList<>();
for (int j = 1; j <= i / 2; j++) {
if (i % j == 0) {
factorList.add(j);
}
}
sum = 0;
for (Integer factor : factorList) {
sum += factor;
}
if (sum == i) {
System.out.println("Found perfect number " + i + " with factors " + factorList);
perfectList.add(i);
}
}
return perfectList;
}
public static void main(String[] args) {
System.out.println(findNPerfectNumbers(4));
}
}
If number is less than 10^1500 you can use Euclid's method
public static List<Long> findPerfect(int n){
List<Long> perfectList=new ArrayList<>();
int x=0;
long sum=0;
long last;
while(perfectList.size()!=n){
last= (long) Math.pow(2,x);
sum+=last;
if(isPrime(sum))
perfectList.add(sum*last);
x++;
}
return perfectList;
}
public static boolean isPrime(long x){
if(x==1)
return false;
for (int i = 2; i <= Math.sqrt(x); i++) {
if(x%i==0)
return false;
}
return true;
}
When I submit my code on Google Kickstart, I get a "wrong answer" for the 1st test set, even though the sample input and output match. I'm really not sure why Google does not accept the code.
The task is that given an array of N positive integers, find the number of K-countdowns, where a K-countdown is a contiguous subarray if it is of length K and contains the integers K, K-1, K-2, ..., 2, 1 in that order.
Input:
The first line of the input gives the number of test cases, T. T test cases follow. Each test case begins with a line containing the integers N and K. The second line contains N integers. The i-th integer is Ai.
Output:
For each test case, output one line containing Case #x: y, where x is the test case number (starting from 1) and y is the number of K-countdowns in her array.
Sample Input:
3
12 3
1 2 3 7 9 3 2 1 8 3 2 1
4 2
101 100 99 98
9 6
100 7 6 5 4 3 2 1 100
Sample Output:
Case #1: 2
Case #2: 0
Case #3: 1
My logic is pretty straightforward: I have a counter variable x which starts at K and decrements whenever an integer equals x. If a countdown is found (x=0 after decrementing) then the answer increases and x is set to equal K. Here is the crux of my code:
for(int i=0; i<n; i++) {
arr[i]=sc.nextLong();
if(arr[i]==x)
x--;
else
x=k;
if(x==0) {
ans++;
x=k;
}
}
Here is my entire code in case there are any trivial errors:
import java.util.Scanner;
public class Solution {
static int t;
static long n,k;
static long[] arr;
static Scanner sc=new Scanner(System.in);
public static void main(String[] args) {
t=sc.nextInt();
for(int i=1; i<=t; i++) {
n=sc.nextLong();
k=sc.nextLong();
System.out.println("Case #"+i+": "+solve());
}
sc.close();
}
public static long solve() {
long x=k;
long ans=0;
arr=new long[(int)n];
for(int i=0; i<n; i++) {
arr[i]=sc.nextLong();
if(arr[i]==x)
x--;
else
x=k;
if(x==0) {
ans++;
x=k;
}
}
return ans;
}
}
here is my cpp code which is running in o(n)
#include<bits/stdc++.h>
using namespace std;
int main(){
int t,m;
cin>>t;
m=t;
while(t--){
int n,k;
cin>>n>>k;
vector <int> v,v2;
for(int i=0;i<n;i++){
int tr;
cin>>tr;
v.push_back(tr);
}
for(int j=0;j<k;j++){
int tr=k-j;
v2.push_back(tr);
}
int fg=0;
for(int i=0;i<n;i++){
if(v[i]==k){
int count=0;
for(int j=0;j<k;j++){
if(v2[j]==v[i+j])
count++;
}
if(count==k)
fg++;
}
}
cout<<"Case #"<<m-t<<": "<<fg<<endl;
}
}
Suppose there is half of a countdown in the array and the following number is K.
Based on the code, that number will be neglected and so if there is a following countdown, it won't be counted. Here is what the main loop should look like:
for (int i = 0; i < n; i++) {
arr[i] = sc.nextLong();
if (arr[i] == x)
x--;
else if (arr[i] == k)
x = k-1;
else
x = k;
if (x == 0) {
ans++;
x = k;
}
}
Here is my Accepted code in java :
import java.util.*;
public class Solution {
public static int kCountDown(int [] nums, int k) {
int length = nums.length;
int endCounter = 0;
int result = 0;
for (int i=1; i<length; i++) {
if (nums[i - 1] - nums[i] == 1)
endCounter += 1;
else
endCounter = 0;
if (nums[i] == 1 && endCounter >= k - 1)
result += 1;
}
return result;
}
public static void main(String [] args) {
Scanner sc = new Scanner(System.in);
int test = sc.nextInt();
for (int t=1; t<=test; t++) {
int n = sc.nextInt();
int k = sc.nextInt();
int [] nums = new int [n];
for (int i=0; i<n; i++) {
nums[i] = sc.nextInt();
}
System.out.println("Case #" + t + ": " + kCountDown(nums, k));
}
}
}
Complexity is O(n) where n = length of the input array
I was practicing with some exercises from UVA Online Judge, I tried to do the Odd sum which basically is given a range[a,b], calcule the sum of all odd numbers from a to b.
I wrote the code but for some reason I don't understand I'm getting 891896832 as result when the range is [1,2] and based on the algorithm it should be 1, isn't it?
import java.util.Scanner;
public class OddSum
{
static Scanner teclado = new Scanner(System.in);
public static void main(String[] args)
{
int T = teclado.nextInt();
int[] array = new int[T];
for(int i = 0; i < array.length; i++)
{
System.out.println("Case "+(i+1)+": "+sum());
}
}
public static int sum()
{
int a=teclado.nextInt();
int b = teclado.nextInt();
int array[] = new int[1000000];
for (int i = 0; i < array.length; i++)
{
if(a%2!=0)
{
array[i]=a;
if(array[i]==(b))
{
break;
}
}
a++;
}
int res=0;
for (int i = 0; i < array.length; i++)
{
if(array[i]==1 && array[2]==0)
{
return 1;
}
else
{
res = res + array[i];
}
}
return res;
}
}
Your stopping condition is only ever checked when your interval's high end is odd.
Move
if (array[i] == (b)) {
break;
}
out of the if(a % 2 != 0) clause.
In general, I don't think you need an array, just sum the odd values in your loop instead of adding them to the array.
Keep it as simple as possible by simply keeping track of the sum along the way, as opposed to storing anything in an array. Use a for-loop and add the index to the sum if the index is an odd number:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter minimum range value: ");
int min = keyboard.nextInt();
System.out.println("Enter maximum range value: ");
int max = keyboard.nextInt();
int sum = 0;
for(int i = min; i < max; i++) {
if(i % 2 != 0) {
sum += i;
}
}
System.out.println("The sum of the odd numbers from " + min + " to " + max + " are " + sum);
}
I don't have Java installed right now, however a simple C# equivalent is as follows: (assign any values in a and b)
int a = 0;
int b = 10;
int result = 0;
for (int counter = a; counter <= b; counter++)
{
if ((counter % 2) != 0) // is odd
{
result += counter;
}
}
System.out.println("Sum: " + result);
No major dramas, simple n clean.
Problem H [Longest Natural Successors]
Two consecutive integers are natural successors if the second is the successor of the first in the sequence of natural numbers (1 and 2 are natural successors). Write a program that reads a number N followed by N integers, and then prints the length of the longest sequence of consecutive natural successors. Example:
Input
7 2 3 5 6 7 9 10 Output 3
here is my code so far can anyone help me plz
import java.util.Scanner;
public class Conse {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
int x=scan.nextInt();
int[] array= new int[x];
for(int i=0;i<array.length;i++)
array[i]=scan.nextInt();
System.out.println(array(array));
}
public static int array(int[] array){
int count=0,temp=0;
for(int i=0;i<array.length;i++){
count=0;
for(int j=i,k=i+1;j<array.length-1;j++,k++)
if(array[j]-array[k]==1)
count++;
else{if(temp<count)
temp=count;
break;}
}
return temp+1;
}
}
Try this
ArrayList<Integer> outList = new ArrayList<Integer>()
int lastNum = array[0];
for(int i = 1; i < array.length; i++;)
if((lastNum + 1) == array[i])
outList.add(array[i]);
I think the line i=counter; should be i += counter. otherwise, you're always resetting the loop-counter i to zero, and so it never progresses.
You don't need the inner for loop, as this can be done with one single scan through the array:
public static int consecutive(int[]array) {
int tempCounter = 1; //there will always be a count of one
int longestCounter = 1; //always be a count of one
int prevCell = array[0];
for(int i=1;i<array.length;i++) {
if( array[i] == (prevCell + 1)) {
tempCounter++; //consecutive count increases
} else {
tempCount =1; //reset to 1
}
if(tempCounter > longestCounter) {
longestCounter = tempCounter; //update longest Counter
}
prevCell = array[i];
}
return longestCounter;
}
int sequenceStart = 0;
int sequenceLength = 0;
int longestSequenceLength = 0;
for (int item: array) {
if (item == sequenceStart + sequenceLength) {
sequenceLength++;
} else {
sequenceStart = item;
sequenceLength = 1;
}
longestSequenceLength = Math.max(longestSequenceLength, sequenceLength);
}
Here's my code:
import java.util.*;
public class factorialdisplay {
// Main Method. Prints out results of methods below.
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
// Asks user for input
System.out.println("Please enter a number: ");
int n = console.nextInt();
for (int i = 0; i <= n; ++i) {
System.out.println(i + "! = " + factorial(n));
}
}
public static int factorial (int n) {
int f = 1;
for (int i = 1; i <= n; ++i) {
f *= i;
return f;
}
return f;
}
}
I'm trying to get the output:
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
But when I run the code, I get this:
0! = 1
1! = 1
2! = 1
3! = 1
4! = 1
5! = 1
My question is, how would I return the result of each iteration of a for loop, through the factorial static method, to the main method?
You need to remove the return f; statement which is there in the for loop. The return within the if will always return to the calling method immediately after the first iteration. And that is why you're getting 1 as the result for all the factorials.
public static int factorial (int n) {
int f = 1;
for (int i = 1; i <= n; ++i) {
f *= i;
// return f; // Not needed - this is causing the problem
}
return f; // This is your required return
}
And as Ravi pointed out
for (int i = 1; i <= n; ++i) { // well 0 will return 1 as well, so no prob unless you don't need 0 factorial
System.out.println(i + "! = " + factorial(i)); // you need to pass i instead of n as i is the counter here
}
Don't return here:
for (int i = 1; i <= n; ++i) {
f *= i;
return f; // here!
}
but rather at the end of your loop. You need to accumulate your final result over all iterations of your loop.
Three problems with the code:
Start at i = 1
Call factorial(i) not factorial(n)
for (int i = 1; i <= n; ++i) { // (1) start at i = 1
System.out.println(i + "! = " + factorial(i)); // (2) pass i not n
}
Return once; after the loop ends
for (int i = 1; i <= n; ++i) {
f *= i;
// return f; // (3) don't return from here
}
return f;
Hmmm... you sort of think of a yield operation (which is available in some languages, but not Java). yield is a construct which says: "return a value from the function, but bookmark the place where I currently am and let me come back to it later". return on the other hand says something like "return the value and discard everything I do". In Java, you can't "put a loop on hold" and come back to it later.
I undestand that what you are trying to achieve is not wasting time by repeating calculations (and just leaving the return which has been proposed in other answers is incredibly bad for performance; justr try it for some bigger numbers...). You could achieve it by not yielding the results, but storing them in an array. Like this:
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
// Asks user for input
System.out.println("Please enter a number: ");
int n = console.nextInt();
int[] results = factorials(n);
for (int i = 0; i <= n; ++i) {
System.out.println(i + "! = " + results[i]);
}
and the function:
public static int[] factorials (int n) {
int[] results = new int[n + 1];
results[0] = 1;
int f = 1;
for (int i = 1; i <= n; ++i) {
f *= i;
results[i] = f;
}
return results;
}
Note that the above could be written better - I tried to modify your code as little as possible.