标题:带分数
100 可以表示为带分数的形式:100 = 3 + 69258 / 714
还可以表示为:100 = 82 + 3546 / 197
注意特征:带分数中,数字1~9分别出现且只出现一次(不包含0)。
类似这样的带分数,100 有 11 种表示法。
题目要求:
从标准输入读入一个正整数N (N<1000*1000)
程序输出该数字用数码1~9不重复不遗漏地组成带分数表示的全部种数。
注意:不要求输出每个表示,只统计有多少表示法!
例如:
用户输入:
100
程序输出:
11
再例如:
用户输入:
105
程序输出:
6
资源约定:
峰值内存消耗(含虚拟机) < 64M
CPU消耗 < 3000ms
思路:条件是表达式中1-9都用到且不重复,为了减少循环想到了全排列,再用p和q控制+号和/号的位置,三重循环验证了所有情况.如果符合条件将count++,然后输出.(注:全排列算法参考了http://blog.csdn.net/java2000_net/article/details/3968189)
import java.util.Scanner;
public class t8{
static int[] array = {1,2,3,4,5,6,7,8,9};
static int r1=0;
static int r2=0;
static int r3=0;
static int count=0;
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
int yh=sc.nextInt();
getAllOrder(0, array.length - 1, yh);
System.out.println(count);
Runtime r = Runtime.getRuntime();
long freeMemory = r.freeMemory();
long totalMemory = r.totalMemory();
long maxMemory = r.maxMemory();
int availableProcessors = r.availableProcessors();
System.out.println(freeMemory);
System.out.println(totalMemory);
System.out.println(maxMemory);
System.out.println(availableProcessors);
}
public static void getAllOrder(int begin, int end, int yh) { //全排列
if (begin == end) {
check(yh);
} else {
for (int i = begin; i <= end; i++) { // 交换数据
swap(begin, i);
getAllOrder(begin + 1, end, yh);
swap(i, begin);
}
}
}
public static void swap(int from, int to) {
if (from == to) {
return;
}
int tmp = array[from];
array[from] = array[to];
array[to] = tmp;
}
public static void check(int yh) { //排列并逐一验证
for(int p=1;p<=7;p++){
for(int q=p+1;q<=8;q++){
r1=0;r2=0;r3=0;
for(int k=0;k<p;k++){
r1*=10;
r1+=array[k];
}
for(int k=p;k<q;k++){
r2*=10;
r2+=array[k];
}
for(int k=q;k<9;k++){
r3*=10;
r3+=array[k];
}
if(yh==(r1+r2/r3)&&r2%r3==0) count++;
}
}
}
}