输入:n,输出:所有+ ve数字最多为n,有4个除数?

时间:2014-11-30 09:18:37

标签: java

当给定整数n时,打印出所有带有4个正除数的n的正数。

示例:

10 --> 6 8 10  
16 --> 6 8 10 14 15

我的代码

public class ass5_q1 {  

public static int divide(int n) 
{
     int x;
     int v = 0;
    for ( x = 1; x <= n; x++ )    
     {
        if ( n % x == 0 )         
        {  
           v++;
        }
     }
     if(v==4)
         System.out.println(v);
     return v;

}
     public static void main(String[] args)

{
     Scanner read = new Scanner(System.in);
     int m;
     m = read.nextInt();
     for(int i=0; i<=m; i++)
     {
         if(i==divide(m))
         {
             System.out.print(i);
         }

     }
   System.out.println();
 }
}

但我找不到正确的代码.. 我该怎么办?

2 个答案:

答案 0 :(得分:2)

 if(v==4)
     System.out.println(v);
 return v;

在任何情况下,您都会返回v,只有return v;时才应v == 4,因此您应将其放在if声明下:

 if(v==4) {
     System.out.println(v);
     return v;
 }
 //Here you should return something that indicates otherwise,
 //think about a special value that has no meaning if v == 4 not satisfied

这就是为什么我们应该{}甚至一行语句,它可以防止像这样的错误

答案 1 :(得分:0)

这是正确的代码

包neew;

import java.util.Scanner;

public class newa

{     public static int divide(int n)     {          int x;          int v = 0;         for(x = 1; x <= n; x ++)
         {             if(n%x == 0)
            {
               v ++;             }          }
        如果(V == 4)         {             的System.out.println(N);         }         返回n;     }

public static void main(String[] args)
{
    Scanner read = new Scanner(System.in);
    int z;
    int x;
    x = read.nextInt();
    for(int r = 1; r<=x; r++)
    {
        z = divide(r);

    }
    System.out.println();
}

}