In: Computer Science
Does this look correct?
Add operation counts - 0.5pt
* f(N) formula (show your work) - 0.5pt
* O(N) reduction - 0.5pt
public static long sum1(int N)//f(N) = ; O(N) =
{
long opCount = 0;
long sum = 0; //1
opCount++;
opCount++;
opCount++;
for(int i = 0; i < N; i++) //2 +
2N
{
sum++; //N
opCount+=2;
}
opCount++;
System.out.println("f(N) = [f(N)=
3N + 4]");
System.out.println("O(N) =
[O(N)=O(N)]");
System.out.println("OpCount :
"+opCount);
return sum; // 1
}
//do comment if any problem arises
//highlighted code is your function
//there are some bugs in given code according to formula f(N)= 3N + 4 which has been fixed
import java.util.Scanner;
class Sum {
public static long sum1(int N)// f(N) = ; O(N) =
{
long opCount = 0;
long sum = 0; // 1
for (int i = 0; i < N; i++) // 2 + 2N
{
sum++; // N
opCount += 3;
}
opCount++;
opCount++;
opCount++;
opCount++;
System.out.println("f(N) = [f(N)= 3N + 4]");
System.out.println("O(N) = [O(N)=O(N)]");
System.out.println("OpCount : " + opCount);
return sum; // 1
}
public static void main(String[] args) {
Sum object = new Sum();
Scanner sc = new Scanner(System.in);
System.out.print("Enter value of N: ");
int N = sc.nextInt();
System.out.println("O(N) = " + object.sum1(N) + "\n");
}
}
Output: