例:
a=2、b=6
out=8
a=3、b=6
out=8
a=7、b=7
out=7
a=4、b=4
out=0
import java.util.Scanner; public class Demo { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int a = sc.nextInt(); int b = sc.nextInt(); if(a%2==0) { a++; } if(b%2==0) { b--; } int n = (b-a)/2+1; System.out.println((a+b)*n/2); } }
迴圈解法:
import java.util.Scanner; public class Demo { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int a = sc.nextInt(); int b = sc.nextInt(); if (a % 2 == 0) { a++; } if (b % 2 == 0) { b--; } int total=0; for (int i = a; i <= b; i += 2) { total +=i; } System.out.println(total); } }
沒有留言:
張貼留言