Advertisements
Advertisements
Question
Write a program to find the sum of the following series:
S = `2/a + 3/a^2 + 5/a^3 + 7/a^4 + ........................... "to n"`
Answer in Brief
Solution
import java.util.*;
public class Q1e
{ public static void main(String args[])
{ int a, i, n = 1, cnt, t, iter = 0;
double term, sum = 0;
Scanner obj = new Scanner(System.in);
System.out.println("Enter the number of terms");
t = obj.nextInt();
System.out.println("Enter the value of a");
a = obj.nextInt();
while (true)
{
cnt = 0; // reset to zero
for (i = 1; i <= n; i++)
{ if (n % i == 0)
cnt++;
if (i == n)break;
}
if (cnt == 2) // if cnt is 2 then the number is prime
{term = i / Math.pow(a, iter);
if (t == iter)
break;
else
sum += term;
}
n++;
}
System.out.println(sum);
}}
shaalaa.com
Is there an error in this question or solution?
Chapter 1.1: Nested Loop - EXERCISES [Page 145]