코딩도장

피보나치 수열 구하기 #2

피보나치 수열이란, 첫 번째 항의 값이 0이고 두 번째 항의 값이 1일 때, 이후의 항들은 이전의 두 항을 더한 값으로 이루어지는 수열을 말한다. 예) 0, 1, 1, 2, 3, 5, 8, 13

피보나치 수열의 n번째 수를 4,294,967,291으로 나누었을 때의 나머지를 출력하는 프로그램을 작성하시오.

정수 n이 입력으로 주어진다. (1 <= n <= 10^100000)

Sample input
5
Sample output
3
Sample input #2
1000000000000000
Sample output #2
3010145777
수학

2014年10月24日 20:32

Kim Jaeju

(追記) (追記ここまで)
댓글 작성은 로그인이 필요합니다.
(注記) 상대에게 상처를 주기보다 서로에게 도움이 될 수 있는 댓글을 달아 주세요.

5개의 풀이가 있습니다.

Java. long자료형을 사용했더니, 100000을 입력했더니 음수가 결과값으로 나오는 오류가 발생하네요 ᅲᅲ.. 도와주실분?

package h_Fibonacci2;
import java.util.Scanner;
public class Secret {
 public static void main(String[] args) {
 Scanner in=new Scanner(System.in);
 System.out.println("Input:");
 long n=in.nextLong();
 long i,a=0l, b=1l, temp=0l, c=4294967291l;
 for(i=1l;i<n;i++){
 temp=a;
 a+=b;
 b=temp; 
 }
 System.out.println("Output:"+(a%c));
 }
}
Input:
100000
Output:-3809483798

2015年02月22日 21:35

Katherine

댓글 작성은 로그인이 필요합니다.
BigInteger를 사용해 보세요. - pahkey, 2015年02月23日 09:58 M D
(注記) 상대에게 상처를 주기보다 서로에게 도움이 될 수 있는 댓글을 달아 주세요.
package rootcucu.codefight;
import java.math.BigDecimal;
public class FibonacciModulo {
 public static class Matrix {
 public final static Matrix ADVANCE[] = new Matrix[]{
 new Matrix(1,0,0,1),
 new Matrix(1,1,1,0),
 new Matrix(2,1,1,1),
 new Matrix(3,2,2,1),
 new Matrix(5,3,3,2),
 new Matrix(8,5,5,3),
 new Matrix(13,8,8,5),
 };
 public static Matrix IDENTITY = new Matrix(1,0,0,1);
 private BigDecimal a, b, c, d;
 Matrix(BigDecimal a, BigDecimal b, BigDecimal c, BigDecimal d){
 this.a = a;
 this.b = b;
 this.c = c;
 this.d = d;
 }
 Matrix(int a, int b, int c, int d){
 this.a = new BigDecimal(a);
 this.b = new BigDecimal(b);
 this.c = new BigDecimal(c);
 this.d = new BigDecimal(d);
 }
 Matrix multiply(Matrix m){
 return new Matrix(
 Matrix.segment(a,b,m.a,m.c),
 Matrix.segment(a,b,m.b,m.d),
 Matrix.segment(c,d,m.a,m.c),
 Matrix.segment(c,d,m.b,m.d));
 }
 Matrix square(){
 return multiply(this);
 }
 public Matrix remainder(String divisorString){
 BigDecimal divisor = new BigDecimal(divisorString);
 return new Matrix(a.remainder(divisor),
 b.remainder(divisor),
 c.remainder(divisor),
 d.remainder(divisor));
 }
 private static BigDecimal segment(BigDecimal q, BigDecimal r, BigDecimal s, BigDecimal t){
 return q.multiply(s).add(r.multiply(t));
 }
 @Override
 public String toString() {
 return "Matrix [a=" + a + ", b=" + b + ", c=" + c + ", d=" + d
 + "]";
 }
 static BigDecimal findNthFibonacciNumber(BigDecimal n){
 Matrix m = Matrix.ADVANCE[1];
 Matrix a = Matrix.IDENTITY;
 while (n.compareTo(BigDecimal.ZERO) > 0){
 if (n.remainder(new BigDecimal(2)).intValue() == 1){
 a = a.multiply(m).remainder("4294967291"); 
 }
 m = m.square().remainder("4294967291");
 n = n.divide(new BigDecimal(2), BigDecimal.ROUND_FLOOR);
 }
 // f(1) = 0, f(2)=1 일 때는 a.d를 출력.
 // f(0) = 0, f(1)=1 일 때는 a.b를 출력.
 return a.d;
 }
 static void findNthFibonacciNumber(int n){
 Matrix m = Matrix.ADVANCE[1];
 int nSave = n;
 Matrix a = Matrix.IDENTITY;
 while (n != 0){
 if (n%2 == 1){
 a = a.multiply(m).remainder("4294967291"); // 
 }
 m = m.square().remainder("4294967291");
 n/=2;
 }
 System.out.println("value = " + a.b);
 n = nSave;
 }
 }
 public static void main(String[] args){
 String[] inputs = new String[]{"5", "1000000000000000",
 "1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
 };
 for (String input:inputs){
 System.out.println("input = " + input);
 System.out.println(Matrix.findNthFibonacciNumber(new BigDecimal(input)).toPlainString());
 System.out.println();
 }
 }
}

2015年04月09日 15:33

rootcucu

댓글 작성은 로그인이 필요합니다.
(注記) 상대에게 상처를 주기보다 서로에게 도움이 될 수 있는 댓글을 달아 주세요.
import java.math.BigInteger;
public class test {
 final static long DIVISOR = 4294967291L;
 static long fib(String S) {
 if (S == "1") {
 return 0L;
 }
 BigInteger N = new BigInteger(S);
 long t1 = 0L;
 long t2 = 1L;
 for (BigInteger i = new BigInteger("3"); i.compareTo(N) <= 0; i = i.add(BigInteger.ONE)) {
 long t3 = (t1 + t2) % DIVISOR;
 t1 = t2;
 t2 = t3;
 }
 return t2;
 }
 public static void main(String[] args) {
 System.out.println(fib("5"));
 System.out.println(fib("1000000000000000"));
 }
}

생각만큼 느리진 않은데.. 왜 답이 틀릴까요T.T

댓글 작성은 로그인이 필요합니다.
(注記) 상대에게 상처를 주기보다 서로에게 도움이 될 수 있는 댓글을 달아 주세요.
import java.util.Scanner;
import java.math.BigInteger;
public class Na{
 public static void main(String[] args){
 Scanner sc = new Scanner(System.in);
 BigInteger a = new BigInteger("0");
 BigInteger b = new BigInteger("1");
 BigInteger c = new BigInteger(a.add(b)+"");
 int i;
 long n = sc.nextLong();
 i = 2;
 while(i <= n){
 a = b;
 b = c;
 c = a.add(b);
 i++;
 }
 BigInteger d = new BigInteger("4294967291");
 BigInteger e = new BigInteger(c.remainder(d)+"");
 if(n == 1)
 System.out.println("1");
 else if(n == 2)
 System.out.println("2");
 else
 System.out.println(e);
 }
}

2018年05月01日 23:20

배혜민

댓글 작성은 로그인이 필요합니다.
(注記) 상대에게 상처를 주기보다 서로에게 도움이 될 수 있는 댓글을 달아 주세요.
public static void main(String[] args) throws Exception {
 Scanner sc = new Scanner(System.in);
 long n = sc.nextInt(); 
 long f0 = 0;
 long f1 = 1;
 long f = 0;
 for (long i=0; i<n; i++) {
 if (n == 1) {
 f = 1; 
 break;
 }
 if (i == n-1) break;
 f = f1 + f0;
 f1 = f0;
 f0 = f;
 }
 System.out.println(f % 4294967291l);
 } // long으로 했는데도 음수 나오넹

2018年05月06日 16:05

정몽준

댓글 작성은 로그인이 필요합니다.
(注記) 상대에게 상처를 주기보다 서로에게 도움이 될 수 있는 댓글을 달아 주세요.

풀이 작성

(注記) 풀이작성 안내
  • 본문에 코드를 삽입할 경우 에디터 우측 상단의 "코드삽입" 버튼을 이용 해 주세요.
  • 마크다운 문법으로 본문을 작성 해 주세요.
  • 풀이를 읽는 사람들을 위하여 풀이에 대한 설명도 부탁드려요. (아이디어나 사용한 알고리즘 또는 참고한 자료등)
  • 작성한 풀이는 다른 사람(빨간띠 이상)에 의해서 내용이 개선될 수 있습니다.
풀이 작성은 로그인이 필요합니다.
목록으로
코딩도장

코딩도장은 프로그래밍 문제풀이를 통해서 코딩 실력을 수련(Practice)하는 곳입니다.

수학 x 6
연관 문제

언어별 풀이 현황
전 체 x 39
python x 21
기 타 x 5
perl x 1
java x 5
cpp x 3
ruby x 1
cs x 2
matlab x 1
코딩도장 © 2014 · 문의 [email protected]
피드백 · 개인정보취급방침 · RSS

AltStyle によって変換されたページ (->オリジナル) /