How to write Fibonacci in one line? [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I would like to know how can I write a program that give me as output the Fibonacci sequence (until N member) in one line?
The real obligation of my problem is do this program in one line. I know how can I do it with recursion but in only one line, I haven't any idea how can I do that.

Well, this might be considered cheating, but it works :
Fib(n) = (Math.pow(Phi,n) – Math.pow(–phi,n)) / Math.sqrt(5);
Where Phi = (1 + sqrt(5)) / 2
Or in other words :
public static int fib(int n) {
return (int)((Math.pow((1+Math.sqrt (5))/2,n)-Math.pow((1-Math.sqrt (5))/2,n))/Math.sqrt (5));
}
It's quite accurate.
Test :
public static void main(String[] args)
{
for (int i = 0; i<20; i++)
System.out.println (fib(i));
}
Output :
0
1
1
2
3
5
8
13
21
34
55
89
144
233
377
610
987
1597
2584
4181
Read more about it here.

Well, here is a one-line JavaScript version of the iterative approach.
function fib(n){var f=[1,1],g=1,h=1,i,t;for(i=2;i<n;i++){t=g+h;g=h;h=t;f.push(t);}return f;}

I expect you are looking for the ternary operator, which lets you compress conditional statements down into a single expression like so:
// returns the nth number in the fibonacci sequence
public static int fib(int n) {
return (n < 2) ? n : fib(n-1) + fib(n-2);
}
P.S.
This should work for both standard seed conditions of
F1 = 1
F2 = 1
or
F0 = 0
F1 = 1
See the Wikipedia article for a complete discussion of the math.

Related

How to separate and rotate numbers in integer? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have a small problem. I think it's simple, but I don't know, how to manage it properly.
I have this simple int:
int birth = 011112;
and I want output to look like this, in this specific format.
"Your birth date is 12.11.01."
I did it with an integer array, but I want only one integer input like this one, not an array.
Could some body help me? Is there any simple method to manage it of, without using loops?
Basically, the conversion of the int representing a date in some format into String should use divide / and modulo % operations, conversion to String may use String.format to provide leading 0.
The number starting with 0 is written in octal notation, where the digits in range 0-7 are used, so the literals like 010819 or 080928 cannot even be written in Java code as int because of the compilation error:
error: integer number too large
int birth = 010819;
However, (only for the purpose of this exercise) we may assume that the acceptable octal numbers start with 01 or 02 then such numbers are below 10000 decimal.
Then the numeric base for division/modulo and the type of output (%d for decimal or %o for octal) can be defined:
public static String rotate(int x) {
int base = x < 10000 ? 0100 : 100;
String type = x < 10000 ? "o" : "d";
int[] d = {
x % base,
x / base % base,
x / (base * base)
};
return String.format("%02" + type + ".%02" + type + ".%02" + type, d[0], d[1], d[2]);
}
Tests:
System.out.println(rotate(011112)); // octal
System.out.println(rotate(11112)); // decimal (no leading 0)
Output:
12.11.01
12.11.01

Is there a way to automatically store integers in an ArrayList using a for loop? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
My main goal is to get an array that consists of the place values of a number.
for example: if the user input is: 35779
I want this array: {3, 5, 7, 7, 9}
(the user input might change and it can range from 10 to the max possible value of an int.
(int counter is an int that represent how many place values does the input number has. example: when input is: 38557: counter = 5)
ArrayList<Integer> obj = new ArrayList<Integer>();
for(int i = counter-1; i >= 0 ; --i){
int ten2pow = (int)Math.pow(10, i);
int x = input/ten2pow;
obj.add(x);
input = input - x*ten2pow;
}
when doing this and trying to print the array, the output is an empty array
Edit: after changing the for loop initialization and termination condition, the loop worked just fine, and I was able to store the Place values in the ArrayList
I'm going to guess the number is given, if it need to be read from console, then I'm leaving that part out.
Suppose our number is: 35779, then a simple way to "divide" it, digit by digit might be:
Get module 10 result of number
Divide number by 10
Example:
Modulus: 9
number: 3577
Repeat:
Modulus: 7
number: 357
So, this can be done this way:
import java.util.ArrayList;
import java.util.List;
public class NumbersToArray {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
int number = 35779;
while (number > 0) {
list.add(0, number % 10);
number /= 10;
}
System.out.println(list);
}
}
Which prints:
[3, 5, 7, 7, 9]
So, there's no need to get the length of the number
As hinted to by Sotirios Delimanolis in the comments on the question, the first issue here is that the for-loop condition is wrong. i <= 1 will never be true if i starts at a number greater than 1. Also, if the statement were ever to be true (i.e., i is 0 or less than 0), then the increment expression (i--) would run until it underflows to Integer.MAX_VALUE.
Alnitak also mentions in the comments that it would be better to start with the least significant digit. This follows the div/mod algorithm for base conversion, which is more conventional.
The div/mod algorithm for base conversion works by recursively taking a modulo b, where, a is the result of the last modulo operation (starting with the source value) and b is the base to convert to. Each iteration provides another digit for the resulting number by its remainder, starting from the right.
Take for example converting 1000 to base 2:
1000 % 2 = 500, R 0 => ?? ???? ???0
500 % 2 = 250, R 0 => ?? ???? ??00
250 % 2 = 125, R 0 => ?? ???? ?000
125 % 2 = 62, R 1 => ?? ???? 1000
62 % 2 = 31, R 0 => ?? ???0 1000
31 % 2 = 15, R 1 => ?? ??10 1000
15 % 2 = 7, R 1 => ?? ?110 1000
7 % 2 = 3, R 1 => ?? 1110 1000
3 % 2 = 1, R 1 => ?1 1110 1000
1 % 2 = 0, R 1 => 11 1110 1000
You can see how the remainders are used to determine the resulting value. The code to use this algorithm here would look something like this:
ArrayList<Integer> numberList = new ArrayList<Integer>();
int iteratedValue = input;
do {
int currentDigit = iteratedValue % 10;
numberList.add(currentDigit);
iteratedValue /= 10;
} while (iteratedValue > 0);
Collections.reverse(numberList);
A do...while loop is used to ensure that the first digit gets added to the list, even if it is 0.
A deque or other collection could be used to add the items in reverse as an alternative to reversing the list at the end.

I tried to write the program, but it is not working the way I want it. Please tell me what am I doing wrong [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
This is the question: Modify the above program to sum all the numbers between 1 to 1000 that are divisible by 7.
This is my code:
int x=1;
int y=1000;
int number=x;
int sum=0;
while (number%7==0) {
sum=sum+number;
++number;
}
System.out.printf("The sum of all numbers divisible by 7 from 1 to 100 is %d", sum);
I don't really like the approach of using a while loop when you know the bounds.
First, start by finding the highest possible :
int maximum = 1000 - 1000 % 7;//994
Then loop from first, until last, by step of 7.
for(int x = 7; x <= maximum; x += 7)
sum += x;
No need to check with slow modulo as we have both bounds and increase by step of 7. Also notice the <=. The = is important here if we want to include the highest.
You could still do it with a while if you want, but in your example you are looping until you find a number which is not divisible by 7. You start at 1, so you will never enter. You need to loop between bounds and verify with an if if the current number is divisible by 7, then you sum.
Again since you know the bounds, the for loop shown above looks cleaner.
For completeness sake, using Java 8 you could achieve this with help of IntStream :
IntStream
.rangeClosed(7, maximum)
.filter(i -> i % 7 == 0)
.sum();
But this will be slower as range only allows incremental of 1 so we process each number and perform a modulo on each.
Try this:
int number=x;
int sum=0;
while (number<y) {
if (number%7==0) {
sum+=number;
}
number++;
}
However there is more effective way. There is no need to loop by one, but loop by 7 and sum these numbers:
int d=7;
int number = (x/d)*d;
int sum=0;
while (number < y-d) {
n+=d;
sum+=n;
}
d represents the divisor.

Custom number in Java [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I would like to create a custom number class in java, which after ranging from 000000 to 099999 would continue with 0A0000. So the last number would be 9Z9999.
I'm a bit lost on how I could implement this in Java. I suppose I would need to create a custom class which extends Number.
My goal would be to create a class on which I could iterate through (from 000000 to 9Z9999) to reserve document ID ranges.
Although I could do achieve this end with several other workarounds, I find this to be the cleanest solution.
Thank you for any help in advance.
This seems to work. Just use an ordinary number and format it:
static String asStrangeNumber ( int i ) {
// Lowest 4 digits are decimal.
int low4 = i%10000;
i /= 10000;
// Next is base 36 - 0-9-A-Z
int c = i % 36;
i /= 36;
// Remaining should be < 10.
return String.format("%1d%c%04d", i%10, c < 10 ? '0' + c: 'A' + c - 10, low4);
}
public void test() {
test (0);
test (1);
test (10);
test (100);
test (1000);
test (10000);
test (100000);
test (1000000);
}
private void test(int i) {
System.out.println(" "+i+" -> "+asStrangeNumber(i));
}
prints
0 -> 000000
1 -> 000001
10 -> 000010
100 -> 000100
1000 -> 001000
10000 -> 010000
100000 -> 0A0000
1000000 -> 2S0000
I don't think it makes sense. Number defines methods like intValue() etc., and how can you convert 0Z0000 to int?
Just create your own CustomId class, but don't extend Number.
The simplest way to do this is to create a single class that gives out IDs (note these are not numbers per se but words). This would contain 6 counters, each of which had a maximum value (9 for 5 of them 36 for the remaining one that has numbers and letters).
When each new ID is requested the bottom counter is increased, when it reaches it's maximum value it resets to zero and increases the next counter by one etc etc. (this counter could be its own class, with fields for currentValue and maximumValue and method increment() that increments the internal value and returns a boolean as to if the higher counter should be incremented)
Then the actual ID is outputted as a String, with each counter having it's current value converted to a single character (0-9 -->'0'-'9' 10-36 --> 'A'-'Z')

Returning the other argument of 2 possible arguments without using conditions [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
For example, if I have a function that is guaranteed to receive either 5 or 7 as an argument, I want the function to return 5 if received 7 and 7 if received 5 without using any conditions.
I was asked this in an interview and was pretty stumped,
thanks.
Simple arithmetic:
return 7 - input + 5;
(which can be simplified as return 12 - input;)
Let's say the input is 7:
return 7 - 7 + 5 --> return 5
Or if the input is 5:
return 7 - 5 + 5 --> return 7
You can use any simple commutative calculation that can be reversed:
addition: f(x)=7+5-x
xor: f(x)=7^5^x
multiplication: f(x)=7*5/x
public int f(int x) {
return x ^ 2;
}
In binary:
7 = 111
5 = 101
2 = 010
XOR (^ in java) flips the 2 bit on if it's off and off if it's on.
How about:
public int q(int in)
{
static final int[] ret = {0, 0, 0, 0, 0, 7, 0, 5};
return ret[in];
}
If I had been the one interviewing and you solved it only for numeric input, my next question would have been, "How would you solve this problem for non-numeric input?" because I wouldn't be looking for mathematical cleverness. Instead, how about this?
List<String> options = new ArrayList<>(Arrays.asList("bob", "fred"));
options.remove("bob");
System.out.println(options.get(0));
That can obviously be easily adapted to any type, including Object, so long as the equality of the objects works out correctly, and as a bonus, it can be expressed much more concisely in other languages, such as Groovy:
println((["bob", "fred"] - "bob").first())
The output, in either case, is obviously "fred". If I were the one interviewing, this is the answer I'd be looking for.
public int xyz(int x) {
return 35 / x;
}
How does the xor one work? [for case f(x) = 7^5^x ]
XOR (^) is Exclusive OR and works this way
a|b|a^b
-------
0|0| 0
0|1| 1
1|0| 1
1|1| 0
So XOR (^) can be used to change bits of some number. For example when we want to change last two bits of any number (like xxxx10 to xxxx01) we can do it with numbrer ^ 3 since 3 is binary 00011.
Here are few facts about XOR
XOR is symmetric -> a^b = b^a
XOR is associative -> (a^b)^c = a^(b^c)
a^a = 0 (ones in a will be replaced with zeros and zeros will be not changed)
example for a = 157 (binary 010011101)
010011101
^ 010011101
-----------
000000000
0^a = a (ones in a can only change zeros so they will change them to ones)
000000000
^ 010011101
-----------
010011101
so using facts (1) and (2) 7^5^x == x^7^5 == x^5^7
Lets try to check how x^7^5 will work for x=7.
(x^7)^5 = (7^7)^5 = 0^5 = 5
And same happens for x=5
(x^5)^7 = (5^5)^7 = 0^7 = 7

Categories

Resources