输入n,a,求Sn=a+aa+aaa+···+a···a(n个a相加)

第一种做法:

public class AddSame {
    public static void main(String[] args) {
        System.out.println("依次输入a和n的值");
        Scanner scanner = new Scanner(System.in);
        int a = scanner.nextInt();
        int n = scanner.nextInt();
        int sum = 0;
        for(int i=1;i<=n;i++){
            sum += a;
            a += (int)Math.pow(10,i);
        }
        System.out.println(sum);
    }
}

第二种简单做法:

a+aa+aaa,可以当作a*3*10^0+a*2*10^1+a*1*10^2
所以可以推出来和sn可以表示为:sn=a*(n-i)*(int)*10^i

public class AddSame {
    public static void main(String[] args) {
        System.out.println("依次输入a和n的值");
        Scanner scanner = new Scanner(System.in);
        int a = scanner.nextInt();
        int n = scanner.nextInt();
        int sum = 0;
        for (int i = 0;i

 

你可能感兴趣的:(输入n,a,求Sn=a+aa+aaa+···+a···a(n个a相加))