首页 > 代码库 > 求从10到100中能被3或5整除的数的和
求从10到100中能被3或5整除的数的和
题目
求从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; }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。