set of integers as input to print sum of their cubes - java

I am trying to solve this question. I tried many different ways, I get the correct output but the testcases are not passed(I dont know what are those testcases). I cant figure what is wrong.
Question:
Given a set of integers (separated by space), write a program to print the sum of their cubes.
Sample Input:
1 2 3 4 5
Sample Output:
225
Sample Input:
1 2
Sample Output:
9
Solution 2:
import java.io.*;
import java.util.*;
class Test{
public static void main(String []args)
{
int num,sum=0;
Scanner sc=new Scanner(System.in);
String data=sc.nextLine();
Scanner sc2=new Scanner(data);
while(sc2.hasNextInt())
{
num=sc2.nextInt();
sum=sum+num*num*num;
}
System.out.print(sum);
}
}

Your test cases most likely contain large integers as input. Use BigInteger to hold their cubes.

I modified my answer according to your needs. Now it gives sum of cubes of numbers in given input which are separated by spaces. Check this :-
import java.math.BigInteger;
import java.util.ArrayList;
import static java.util.Collections.list;
import java.util.List;
import java.util.Scanner;
public class SumOfCubes {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
String integers="";
Integer num=0;
BigInteger cube;
BigInteger sum=new BigInteger("0");
System.out.println("Enter Integers seperated by space");
integers=in.nextLine();
List<Integer> list = new ArrayList<Integer>();
for (String s : integers.split("\\s")) {
list.add(Integer.parseInt(s));
}
list.toArray();
for(int i=0;i<list.size();i++){
num=list.get(i);
cube=BigInteger.valueOf(num*num*num);
sum=sum.add(cube);
}
System.out.println("Sum of Cubes of numbers in given input = "+sum);
}
}
Hope it helps.

Update (by Andreas): Added boilerplate imports since #Ash seems unable to figure that out.
If you would like an implementation in more functional style (using Java 8+ streams), here is another suggestion:
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String line = scan.nextLine();
String[] numbers = line.split("\\s+");
BigInteger sum = Arrays.asList(numbers)
.stream()
.map(BigInteger::new)
.map(bigInteger -> bigInteger.pow(3))
.reduce(BigInteger.ZERO, BigInteger::add);
System.out.println(sum);
}
}
Update: After #Andreas comments, the implementation can be even shorter:
import java.math.BigInteger;
import java.util.Scanner;
import java.util.regex.Pattern;
public class Test {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String line = scan.nextLine();
BigInteger sum = Pattern.compile("\\s+")
.splitAsStream(line)
.map(s -> new BigInteger(s).pow(3))
.reduce(BigInteger::add)
.orElse(BigInteger.ZERO);
System.out.println(sum);
}
}

I have changed your Solution 2 a little bit. Could you please confirm whether this passes the test or not.
import java.math.BigInteger;
import java.util.Scanner;
public class Test{
public static void main(String []args)
{
BigInteger sum=new BigInteger.ZERO;
Scanner sc=new Scanner(System.in);
String data=sc.nextLine();
Scanner sc2=new Scanner(data);
while(sc2.hasNextInt())
{
BigInteger num=new BigInteger(String.valueOf(sc2.nextInt()));
sum= sum.add(num.multiply(num).multiply(num));
}
System.out.print(sum);
}
}

import java.util.*;
class csum
{
public static void main(String args[])
{
Scanner in=new Scanner(System.in);
long csum=0;
while(in.hasNextInt())
{
csum=csum+(long)Math.pow(in.nextInt(),3);
}
System.out.println(csum);
}
}

public static void main(String args[])
{
long num,count=0;
Scanner in=new Scanner(System.in);
while(in.hasNextInt())
{
num=in.nextInt();
count+=Math.pow(num,3);
}
System.out.println(count);
}
or
public Static vid main(String args[])
{
long count;
Scanner in=new Scanner(System.in);
String s=in.nextLine();
String[] t=s.split(" ");
for(i=0;i<t.length;i++)
{
count+=Math.pow(Integer.parseInt(t[i]),3);
}
System.out.println(count);
}

Used long instead of int. Thanks to Andreas and Matsev for the BigInteger idea.
import java.util.*;
class Test{
public static void main(String []args)
{
long num,sum=0;
Scanner sc=new Scanner(System.in);
String data=sc.nextLine();
Scanner sc2=new Scanner(data);
while(sc2.hasNextInt())
{
num=sc2.nextInt();
sum=sum+num*num*num;
}
System.out.println(sum);
}
}

Related

Convert number to reversed array of digits (Scanner + Print-Method)

I want to get an Array with the reversed number when I invoke the method (Given a random non-negative number, you have to return the digits of this number within an array in reverse order.)
I initalised a scanner, but whenever I execute, I only get the address in the heap I suppose (for example: [I#66a29884).
I know this problem also occurs when we have String, which why we have the toString-Method.
Is there a way I can print the array or the reversed numbers out in the console?
public class ConvertNumber {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Long n = Long.parseLong(scanner.nextLine());
digitize(n);
}
public static int[] digitize(long n) {
int[] digitized = new StringBuilder().append(n).reverse().chars().map(Character::getNumericValue).toArray() ;
System.out.println(digitized);
return digitized;
}
}
You have to change Long to String because [I#66a29884) is String. using java stream you can reverse string easily.
import java.util.stream.Stream;
import java.util.stream.Collectors;
import java.util.*;
public class Main
{
public static String digitize(String n) {
return Stream.of(n)
.map(str->new StringBuilder(str).reverse())
.collect(Collectors.joining(" "));
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String n = scanner.next();
System.out.print(digitize(n));
}
}

how to scan many time by using for function?

import java.util.Scanner;
public class array2 {
public static void main(String[]sef)
{
int a=0;
int number[]=new int[20];
Scanner scan=new Scanner(System.in);
for(a=0;a<number.length;a++); //**i want scan data many time**
{
System.out.println(a+"번째 학생의 숫자를 입력하십시오");
number[a]=scan.nextInt();
}
scan.close();
for(a=0;a<10;a++)
{
System.out.println(number[a]);
}
}
}
i want to input data in arr many time. but i don't know how to do and i don't find answers in my language
I found some bugs in your code and I have added a few things to it. You can have a look at the snippet below.
import java.util.Arrays;
import java.util.Scanner;
public class array2 {
public static void main(String[] args) {
int number[] = new int[5];
Scanner scan = new Scanner(System.in);
for (int a = 0; a < number.length; a++) {
System.out.println(a + "번째 학생의 숫자를 입력하십시오");
System.out.println("Please Enter a number");
number[a] = scan.nextInt();
}
System.out.println(Arrays.toString(number));
scan.close();
}
}

BigInteger Factors in java

So i am trying to find all the factors of a large number i.e 10^15.Where am i going wrong?
I just input test cases then the large number and i need all the factors of that number.
this is my code
import java.io.*;
import java.math.*;
import java.util.*;
class GFG {
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
int test = sc.nextInt();
int blue[];
int siize;
BigInteger babe;
int count=0;
for(int i=0;i<test;i++){
babe = sc.nextBigInteger();
for(BigInteger j=BigInteger.ONE;j.compareTo(babe)<=0;j.add(BigInteger.ONE)){
if(babe.mod(j).equals(BigInteger.ZERO)){
System.out.print(j+" ");
}
}
System.out.println();
}
}
}

Unable to resolve NoSuchElementException

I am getting NoSuchElementException while executing my code on various online IDE. I am taking STDIN using Scanner object.
import java.util.*;
import java.util.Scanner;
class Maze{
public static int numberLength(int k){
int ln = (int) (Math.log10(k) + 1);
return ln;
}
public static void main(String [] args){
Scanner kb = new Scanner(System.in);
int n = kb.nextInt();
int s = numberLength(n);
System.out.println(s);
}
}
You have to check Custom input and write your input, then compile
You have got to give inputs for your primitives which you have declared in the main.

change a scanner to a char variable instead of a int or double data type

import java.io.*;
import java.util.*;
public class Test
{
public static void main(String args[])
{
Scanner kbr = new Scanner(System.in);
System.out.print("Enter Player's Name: ");
double n = kbr.nextInt();
System.out.print(n);
}
}
Can I change this to
char n = kbr.nextInt()
or
how can I get it to look for a character string instead of an int.
you can do this as alternative:
import java.io.*;
import java.util.*;
public class Test
{
public static void main(String args[])
{
try{
Scanner kbr = new Scanner(System.in);
System.out.print("Enter Player's Name: ");
String n = kbr.readLine();
//int z = Integer.parseInt();
char z = n.charAt(0);
System.out.print(n);
}
catch(IOException e){
System.out.printl("IO ERROR !!!");
System.exit(-1);
}
}
}
Something like this?
import java.io.*;
import java.util.*;
class Test
{
public static void main(String args[])
{
Scanner kbr = new Scanner(System.in);
System.out.print("Enter Player's Name: ");
String n = kbr.nextLine();
System.out.print(n);
}
}
If you wants to get only first character of the typed string then
char c = kbr.next().charAt(0);
works fine.
However it allows to input more than single character but as soon as you hit enter,
it will store first character in char c.
For example
import java.io.*;
import java.util.*;
class Test
{
public static void main(String args[])
{
Scanner kbr = new Scanner(System.in);
System.out.print("Enter Character: ");
char n = kbr.next().charAt(0);
System.out.print(n);
}
}
Input: Hello
Output: H

Categories