简体   繁体   中英

How to find the product of the first 16 multiples of 2 starting with 2?

I need to find the first 16 multiples of 2 starting with 2. Then find the product in the next line like this. I need to use for loops only.

Sample output: 2 4 6 8 10 12...

The product is ______

I tried this. For loops only.

import java.util.Scanner;
public class Program30
{
    public static void main(String args[]) {
        int a,b;
        b=2*4*6*10*12*14*16*18*20*22*24*26*28*30*32;
        for(int x=1;x<=16;x++) {
            a=2*x;
            
           System.out.print(a+" ");
           
           
           
            
        
}
System.out.println("\nThe product is "+b);
}
}

Is there a better way to do this? Thank you.

On the hardcoded try you are missing the number 8.

 public static void main(String[] args) {
     long a;
     long b = 1L;
     for (int x = 1; x <= 16; x++) {
        a = 2L * x;
        b *= a;
        System.out.print(a + " ");
     }
     System.out.println("\nThe product is " + b);
  }

It is unclear exactly what you want to do with both a and b . But you are doing several things incorrectly which can cause some problems.

  • ints are not large enough to hold the product. So you need to declare them as longs. And intialize a to 1
  • b=2*4*6*10*12*14*16*18*20*22*24*26*28*30*32; Won't sum correctly since the addition is using ints. So set the first value to a long like so using 2L . This will force long conversion. b=2L*4*6*8*10*12*14*16*18*20*22*24*26*28*30*32; You were also missing an 8 .
  • a = 2*x; keeps overwriting the previous value. What you want is a = a * 2*x

Here is the modified code.

public static void main(String args[]) {
     long a = 1,b;
     b=2L*4*6*8*10*12*14*16*18*20*22*24*26*28*30*32;
     for(int x=1;x<=16;x++) {
         a = a *2*x;
         System.out.println(a+" ");                 
     }
     System.out.println("\nThe product for a is "+a);
     System.out.println("\nThe product for b is "+b);
}

prints

2 
8 
48 
384 
3840 
46080 
645120 
10321920 
185794560 
3715891200 
81749606400 
1961990553600 
51011754393600 
1428329123020800 
42849873690624000 
1371195958099968000 

The product for a is 1371195958099968000

The product for b is 1371195958099968000

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM