For 循环不循环到倒数第二个?

问题描述 投票:0回答:1

我昨天正在做这个,但一直没能得到 91 的两个素因数。所以我只是作弊了一点,只是为了提交考试。我现在正在回顾它,看看我是否能让它真正发挥作用。

//made this code for a java test
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int num, fact1 = 0, fact2 = 0;
        
        System.out.print("Enter a number: ");
        num = scan.nextInt();
        int check = num;
        System.out.print("Prime factors of "+num+" (excluding multiples of 3): ");
        
        for (int i=2; i<num; i++) {
            //System.out.println("numfirst: "+num);
            //System.out.println("ifirst: "+i);
            if (i%3==0) {
                continue;
            } else {
                while (num%i==0) {
                    num = num/i;
                    //System.out.println("num: "+num);
                    //System.out.println("i: "+i);
                    if (fact1 != 0) {
                        fact2 = i;
                    } else {
                        fact1 = i; 
                    }
                }
            }
        }
        if (fact2 > 0) {
            System.out.print(fact1+" "+fact2);
        } else {
            System.out.print(fact1+" ");
        }
    }
}

我添加了 souts 来检查增量,并惊讶地发现它只增加到 12???仅比 13(预期的第二个因子)低一级,循环就结束了。我很好奇为什么没有达到 90,因为 90 是 91 之前的最后一个数字。我必须从 i<=num to make it work. It's weird.

编辑 for 循环条件
java for-loop
1个回答
0
投票
public static void main( String[] args ) {
   Scanner scan = new Scanner( System.in );
   int num, fact1 = 0, fact2 = 0;
   System.out.print( "Enter a number: " );
   num = scan.nextInt();
   // delete "check"
   System.out.print( "Prime factors of " + num + ": " );
   int limitA = num / 3 + 1, limitB = num / 3 * 2 + 1;
   for( int i = 3; i < limitA / 3; i ++ ) {
      // we verify that the chosen number is a prime number
      if( ! isPrime( i ) ) {
         continue;
      }
      fact1 = i;
      for( int k = 2; k < limitB; k ++ ) {
         // we verify that the chosen number is a prime number
         if( ! isPrime( k ) ) {
            continue;
         }
         fact2 = k;
         // we check if we have the right result
         if( fact1 * fact2 == num ) {
            System.out.print( fact1 + " and " + fact2 );
            return;
         }
      }
   }
   System.out.println( "not" );
}

static boolean isPrime( int number ) {
   if( number == 2 ) {
      return true;
   }
   // if "number" is even, return false
   if( number % 2 == 0 ) {
      return false;
   }
   for( int i = 3; i * i <= number; i += 2 ) {
      if( number % i == 0 ) {
         return false;
      }
   }
   return true;
}
© www.soinside.com 2019 - 2024. All rights reserved.