码迷,mamicode.com
首页 > 其他好文 > 详细

求从10到100中能被3或5整除的数的和

时间:2014-08-08 21:36:26      阅读:298      评论:0      收藏:0      [点我收藏+]

标签:style   os   io   for   ar   size   ef   table   

题目

求从10到100中能被3或5整除的数的和

解答

解答一

public class Test {
 
    public static void main(String[] args) {
         
        int sum = 0;
        for (int i = 10; i < 100; i++) {
            if (i % 3 ==0 || i % 5 == 0) {
                sum += i;
            }
        }
        System.out.println(sum);
    }
 
}

解答二

/**
 * @brief count tot nums val in 10~100 which 10%3 = 0 or 10%5 = 0
 * @param void
 * @return tot nums
 */
#include <stdio.h>
#define DEBUG 1
int table[120];

#define END     100

#define BASE3   12
#define STEP3   3

#define BASE5   10
#define STEP5   5

int solve(void){
    int sum = 0;
    int pos3 = BASE3;
    int pos5 = BASE5;
    while(pos3 < 100){
            if(pos5 < 100){
                table[pos5] = 1;
                sum += pos5;
                pos5 += STEP5;
            }
            if(!table[pos3]){
                sum += pos3;
            }
            pos3 += STEP3;
    }
    return sum;

}

int main(void){
    printf("%d\n", solve());
    return 0;
}

解答三

/**
 * @brief count tot nums val in 10~100 which 10%3 = 0 or 10%5 = 0
 * @param void
 * @return tot nums
 */
#include <stdio.h>

#define END     100

#define BASE3   12
#define STEP3   3

#define BASE5   10
#define STEP5   5

#define BASE15  15
#define STEP15  15

int solve(void){
    int sum = 0;
    int pos3 = BASE3;
    int pos5 = BASE5;
    int pos15 = BASE15;
    while(pos3 < 100){
            sum += pos3;
            pos3 += STEP3;

            if(pos5 >=  100){
                continue;
            }

            sum += pos5;
            pos5 += STEP5;
        
            if(pos15 >= 100){
                continue;
            }

            sum -= pos15;
            pos15 += STEP15;
    }
    return sum;
}

int main(void){
    printf("%d\n", solve());
    return 0;
}


求从10到100中能被3或5整除的数的和,布布扣,bubuko.com

求从10到100中能被3或5整除的数的和

标签:style   os   io   for   ar   size   ef   table   

原文地址:http://my.oschina.net/u/572632/blog/299389

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!