In Java, write code that sums the integers 1-1,000.000 according to each of the
ID: 3873155 • Letter: I
Question
In Java, write code that sums the integers 1-1,000.000 according to each of the algorithms.
How long does each algorithm takes using n= 1,000.000.
State clearly and precisely how you would plot the number of basic operations (ordinate) vs. n (abscissa) using your program as a basis for getting the required data and Implement the what you proposed.
Algorithm A Algorithm B Algorithm C sum = n * (n + 1) / 2 sum = 0 for i- 1 to n sum = 0 for i = 1 to n sum = sum + i | { for j = 110 i i-1 to sum = sum + 1Explanation / Answer
/* package whatever; // don't place package name! */
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class CalculateSum
{
public static void main (String[] args) throws java.lang.Exception
{
int n=1000;
float sum=0;
Scanner Sc=new Scanner(System.in);
for(int i=1;i<=n;i++)
{
sum=sum+i;
}
System.out.println("Sum is "+sum);
}
}
Output:
Source Code:
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class CalculateSum
{
public static void main (String[] args) throws java.lang.Exception
{
int n=1000;
float sum=0;
Scanner Sc=new Scanner(System.in);
for(int i=1;i<=n;i++)
{
for(int j=1;j<=i;j++)
{
sum=sum+1;
}
}
System.out.println("Sum is "+sum);
}
}
Output:
Source Code:
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class CalculateSum
{
public static void main (String[] args) throws java.lang.Exception
{
int n=1000;
float sum=0;
Scanner Sc=new Scanner(System.in);
sum=n*(n+1)/2;
System.out.println("Sum is "+sum);
}
}
Output:
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.