7.11- Loop structure exercises
1. Determine how many prime numbers are between 2-100 and output all prime numbers.
public class zy01 {
public static void main(String[] args) {
int s=0;
for (int i = 2; i <=100 ; i++) {
for (int j = 2; j <i ; j++) {
s = i%j;
if (s==0){
break;
}
}
if (s!=0){
System.out.print(+i+" ");
}
}
}
}
2. Print out all the "daffodil numbers", the so-called "daffodil number" refers to a three-digit number,
- The sum of the cubes of the digits is equal to the number itself.
- For example: 153 is a "daffodil number"
- Because 153 = 1 cube + 5 cube + 3 cube.
public class zy02 {
public static void main(String[] args) {
for (int i = 100; i <1000 ; i++) {
int a = i/100%10;
int b = i/10%10;
int c = i%10;
if (i==a*a*a+b*b*b+c*c*c){
System.out.print(+i+" ");
}
}
}
}
3. Find the value of s=a+aa+aaa+aaaa+aa...a, where a is a number.
- For example, 5+55+555+5555+55555 (at this time, 5 numbers are added together).
public class zy03 {
public static void main(String[] args) {
System.out.print("输入1-9之间的一个数:");
Scanner sc = new Scanner(System.in);
double n=sc.nextInt();
double k=n;
double sum =n;
for (int i = 1; i <=n-1 ; i++) {
k = k+n*Math.pow(10,i);
sum =sum+k;
}
System.out.println(+sum);
}
}
4. Decompose a positive integer into prime factors. For example: input 90 and print out 90=2 3 3*5.
- To decompose the prime factors of n, you should first find the smallest prime number k, and then complete the following steps:
- (1) If this prime number is exactly equal to n, it means that the process of decomposing prime factors has ended, just print it out.
- (2) If n is not equal to k, but n is divisible by k, the value of k should be printed out, and the quotient of n divided by k should be used as a new positive integer n, and repeat the first step.
- (3) If n is not divisible by k, use k+1 as the value of k, and repeat the first step.
public class zy04 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.print("请输入一个正整数:");
int num=sc.nextInt();
System.out.print(num+"=");
int k=2;
int g =2;
int num1 = num;
do{
if(num%k==0){
System.out.print(k+"*");
num/=k;
}else{
k=k+1;
}
}while(num!=k);
System.out.print(k+"\n");
if(num1==k){
num=num+1;
System.out.print("num+1的值作为k的值重新计算:");
System.out.print(+(num)+"=");
do{
if(num%g==0){
System.out.print(g+"*");
num/=g;
}else{
g=g+1;
}
}while(num!=g);
System.out.print(g);
}
}
}
5. If a number is exactly equal to the sum of its factors, this number is called "final number".
- For example, 6=1+2+3. Programming to find all the numbers within 1000
public class zy05 {
public static void main(String[] args) {
for (int i = 1; i <1000 ; i++) {
int k=0 ;
for (int j = 1; j <i ; j++) {
if (i%j==0){
k = k+j;
}
}
if (i==k) {
System.out.println(+i);
}
}
}
}