這裏很明顯,你不需要將值存儲在矩陣,因爲它是不可能有那麼大的空間(Array[10000][10000]
)來分配。所以你需要用mathematical
的方式來思考。
考慮一個4x4
矩陣和代表的i,j
術語的每個元素。
1,1 1,2 1,3 1,4
2,1 2,2 2,3 2,4
3,1 3,2 3,3 3,4
4,1 4,2 4,3 4,4
現在我們可以在這裏表示存儲在每個元素中的內容。
1/1 1/2 1/3 1/4 (In Integers) 1 0 0 0
2/1 2/2 2/3 2/4 ============> 2 1 0 0
3/1 3/2 3/3 3/4 3 1 1 0
4/1 4/2 4/3 4/4 4 2 1 1
通過將其分成列解決這個矩陣和解決每個columns
的。 對於第一列系列將1+2+3+4
。然後對列號two(2)
系列將0+1+1+2
。
請注意,對於ith
列first
i-1
值爲零,然後i values
在列中相同。然後value
增加。 i
值也是一樣。再次增加1
等。
所以在ith
列值獲得increased
的jth
元素,其中j%i==0
上。
所以你可以在1-D
數組中實現這個邏輯,對於每個測試用例,這種方法的複雜度將是O(n logn)
。
代碼:
import java.util.Scanner;
public class Main
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int testcases=sc.nextInt();
while(testcases-- >0)
{
int n=sc.nextInt();
long array[]=new long[n+1]; //Take long array to avoid overflow
for(int i=1;i<=n;i++)
{
for(int j=i;j<=n;j+=i)
{
array[j]++; //This will store that which elements get increased
//from zero how many times
}
}
//Now we can do summation of all elements of array but we need to do prefix sum here
long sum=0;
for(int i=1;i<=n;i++)
{
array[i]+=array[i-1];
sum+=array[i];
}
System.out.println(sum);
}
}
}
I> = 1且j> = 1。 – iamvroon