user489736 user489736 - 5 months ago 18
Java Question

Project Euler #1: Multiples of 3 and 5

I just tried to solve the Problem 1 of the Project Euler but I am getting java.util.NoSuchElementException.What is wrong with this code?Can any one please help?


problem:If we list all the natural numbers below 10 that are multiples >of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

Find the sum of all the multiples of 3 or 5 below .

Input Format

First line contains T that denotes the number of test cases. This is >followed by T lines, each containing an integer N, .
Output Format

For each test case, print an integer that denotes the sum of all the >multiples of 3 or 5 below N.


import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
int t=in.nextInt();
int n[]=new int[t];
int sum[]=new int[t];
for(int i=0;i<t;t++)
{
n[i]=in.nextInt();
}
for(int i=0;i<t;t++)
{
sum[i]=0;
for(int j=2;j<n[i];j++)
if(j%3==0||j%5==0)
sum[i]+=j;
System.out.println(sum[i]);
}
}
}

Answer

In both of your for loops you are increasing t not i.

for(int i=0;i<t;t++)

Should be

for(int i=0;i<t;i++)