代码
import java.util.Scanner;public class Main {public static void main(String args[]){Scanner sc = new Scanner(System.in);int k = sc.nextInt();int n = 0;double Sn = 0;while(Sn<=k){n++;Sn = Sn + 1.0/n;}System.out.println(n);}
}
这样写while循环体这需要每次加上1/n最后一项就行了,不会超时。
再康康我第一次写的:
import java.util.Scanner;public class luogu1035 {public static void main(String args[]){Scanner sc = new Scanner(System.in);int k = sc.nextInt();int n = 1;while(Sum(n)<=k){n++;}System.out.println(n);}public static double Sum(int n){double sum = 0.0;int i = 1;for (i = 1;i<=n;i++){sum = sum + 1.0/i;}return sum;}
}
直接超时。
我脑袋被门踢了,编写Sum()求和。