![](/img/trans.png)
[英]how to get any integer in a sorted array of size n that appear more than n/k times, given that 0 < k < n, and in O(k log n) time in java?
[英]How to compute approximate natural log of 2 n times in java?
指令是: 1. 通過將系列中的 n 項相加來計算 2 的 ln。 a) 你可以用一個級數來近似 2 的自然對數。 你使用的術語越多,你就越接近 2 的自然對數。 b) ln 2 = 1 - 1/2 + 1/3 - 1/4 + 1/5 - ... 1/nc) 你需要使用 For 循環來解決這個問題 d) 對於這個程序,你將只傳遞 1 個參數,即 n 的值。 e) 您需要弄清楚如何為每個連續的術語更改符號。 這並不難,但需要一些思考。
如果這聽起來不太好,請原諒我,我的英語不是最好的。 到目前為止,我的代碼是這樣的:即使我知道我做錯了很多。 我知道這是錯誤的,但我不知道從哪里開始或如何更改標志。 起初我認為我們需要找到不同數字的 ln,但后來知道它是輸入 n。 編輯:我相信我知道我做錯了什么主要部分。 我盡我所能解決了這個問題。 我現在有點卡住了,因為我在腦子里玩弄邏輯,我相信它應該有效。 相反,它打印出來的只是 1.0 1.0 1.0 1.0 1.0
誰能幫忙指出我做錯了什么?
公共類 aprox_log {
static double findLog (int n)
{
double ln = 1;
for (int i = 1; i <= n; i++)
{
for (int k = 0; i <= n; k++) {
if ((k%2) == 0)
ln = ln - (1/i);
ln = ln + (1/i);
}
}
return 1 - ln;
}
public static void main(String[] args) {
//These lines print the results of test inputs.
System.out.println(findLog(2)); //~0.69314718056
System.out.println(findLog(5)); //~1.60943791243
System.out.println(findLog(10)); //~2.30258509299
System.out.println(findLog(9)); //~2.19722457734
System.out.println(findLog(1)); //0
}
}
新代碼:
public class aprox_log {
static double findLn (int n)
{
double ln = 0;
for (int i = 1; i <= n; i++)
{
if (i%2 == 0)
ln = ln - (1/i);
ln = ln + (1/i);
}
return ln;
public static void main(String[] args) {
//These lines print the results of test inputs.
System.out.println(findLn(2)); //0.5
System.out.println(findLn(5)); //0.783333333
System.out.println(findLn(10)); //0.64563492063
System.out.println(findLn(9)); //0.74563492063
System.out.println(findLn(1)); //1
}
}
`
要找到具有n
項的交替調和級數的總和,只需遍歷從 1 到n
的整數。 然后,如果是奇數,則加上當前數的倒數,如果是偶數,則減去該數的倒數。
static double findLog(int n){
double res = 0;
for(int i = 1; i <= n; i++) res += 1d / (i % 2 == 0 ? -i: i);
return res;
}
在 Java 中,運算符/
以給定數字的精度計算結果。 特別是,如果我們將兩個int
,結果將表示為int
,如果結果不能准確表示,則向 0 舍入。 也就是說, 1 / 2
是0
。
如果您需要浮點精度,則應使用浮點數,例如將i
聲明為double
類型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.