Count the number of eligible elements (Java)

Count the number of odd and even numbers of elements divisible by 3 in the closed interval of 1...n

Input format:

The range of input value n is [1..1000]

Output format:

odd number, even number

Input sample:

5

Sample output:

1,0

AC code:

import java.util.Scanner;

public class beishuzhengchu {
        public static void main(String[] args) {
            Scanner sc=new Scanner(System.in);
            int n=sc.nextInt();
            int m=0,w=0;//用m统计偶数,n记录奇数个数
            for(int i=1;i<=n;i++){
                if(i%3==0){//若能被3整除
                    if(i%2==0){
                        m++;
                    }
                    else{
                        w++;
                    }
                }
            }
            System.out.println(w+","+m);
        }
}

 

Guess you like

Origin blog.csdn.net/weixin_51472673/article/details/123615977