Editorial for Necklace Problem


Remember to use this editorial only when stuck, and not to copy-paste code from it. Please be respectful to the problem author and editorialist.

Submitting an official solution before solving the problem yourself is a bannable offence.

Authors: David

Solution

import java.util.Scanner;

public class NecklaceProblem {

  public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();
    for (int i = 0; i < n; i++) {
      int a = sc.nextInt();
      int b = sc.nextInt();
      // Keep track of original numbers, we will compare to this after each iteration.
      int c = a;
      int d = b;
      int temp;
      // First print out the first number.
      System.out.print(a + " ");
      do {
        // "b" will change to our new number after each iteration.
        System.out.print(b + " ");
        // Get some of last 2 numbers.
        temp = a + b;
        // The new second last number for next iteration is our current last number.
        // The current second last number is no longer needed.
        a = b;
        // New number to print is the ones digit of the sum.
        b = temp % 10;
      }
      while (a != c || b != d);
      System.out.print(b + " ");
      System.out.println();
    }

  }

}

Comments

There are no comments at the moment.