It's been about half a year since I started writing python code, and I've become accustomed to thinking about algorithms, so when I wrote the Fibonacci sequence code and muttered on Twitter, from a senior high school alumnus "Fibonacci often goes to training and exams, so it's better to be able to write in various languages." Since I received the advice, I decided to display it in a language other than python, and in the process I decided to discover the features of each language.
Display method The explanation about the Fibonacci sequence is omitted. If you don't know, google (round throw) The sequence to be displayed shall start with [1,1], enter a numerical value, and if it is 2 or less, it will be displayed as [1,1]. If it is 2 or more, the sequence [1,1, ~~, n] of the input numerical value is output.
python
001.py
l = [1,1]
i = int(input("Please enter the length of the sequence"))
if i < 2:
print(l)
else:
for f in range(2,i):
l.append(l[f-1]+l[f-2])
print(l)
I feel that array relationships are easier to write than in other languages.
Java
001.java
import java.io.InputStreamReader;
import java.util.Scanner;
public class _main_ {
public static void main(String[] args){
int n1 =1;
int n2 =1;
int n3;
System.out.print("Please enter the length of the sequence you want to find\n");
Scanner scanner = new Scanner(System.in);
int a = scanner.nextInt();
if (2 < a){
System.out.print(n1+" "+n2+" ");
for(int x=2;x<a;x++){
n3= n1 + n2;
System.out.print(n3+" ");
n1 = n2;
n2 = n3;
}
}
}
}
I haven't studied much about java, so it's probably crazy. The method is to output n3, which is the sum of n1 and n2, and then replace the numbers.
C++
001.cpp
#include <stdio.h>
int main(void) {
int x = 2;
int i[255] = { 1, 1 };
printf("Enter the number in the sequence you want to find");
scanf_s("%d", &x);
if (x < 3) {
printf("%d %d", i[0], i[1]);
}
else if (255 < x)
printf("A value higher than the specified value has been entered");
else
{
for (int n = 2; n < x; n++) {
i[n] = i[n - 2] + i[n - 1];
}
for (int v = 0; v < (sizeof(i) / sizeof(i[0]))-1; v++) {
if (i[v] != 0)
printf("%d ", i[v]);
else
break;
}
}
return 0;
}
I tried to build it based on the python method, but c ++ has a restriction that the length of the array must be decided from the beginning, so I was quite annoyed. I tried a method to match the maximum value with the entered value, but it didn't work, so I gave up.
*** What I found after writing *** ・ Python is easier than other languages
・ I feel that it will be a little easier to write if I know how to determine the maximum value of an array with variables in C ++.
・ In the future, I would like to be able to write in various languages such as javascript julia, which I started to touch.
・ I think there is a way to make C ++ and java code even easier, so I want to study and improve the quality of the code.
Recommended Posts