Looping. Why is this happening? Prime Numbers - numbers

I'm having a problem understanding the looping, when I put the System.out.println("Looping: " + i); at the start of the for in method.
It loops three times, more than usual, for example with the number 13, it says:
Looping: 2 , Looping: 2, Looping 3.
But instead if I put System.out.println("Looping: " + i); at the end of the for in method, it appears:
Looping 2, Loopin 3
which is the more accurate to my understanding.
Why is this happening?
public static void main(String[] args) {
int counter = 0;
for(int i=1; i <= 10; i++){
if(isPrime(i)){
System.out.println("The number: " + i + " is a prime number");
counter++;
}
if(counter==3){
break;
}
}
public static boolean isPrime(int n){
if(n == 1){
return false;
}
for(int i=2; i <= (long) Math.sqrt(n); i++){
System.out.println("Looping: " + i);
if(n%i == 0){
return false;
}
}
return true;
}

Let take this code:
public static boolean isPrime(int n){
if(n == 1){
return false;
}
for(int i=2; i <= (long) Math.sqrt(n); i++){
System.out.println("Looping: " + i); // first
if(n%i == 0){
return false;
}
System.out.println("Looping2: " + i); // second
}
return true;
}
It's output is:
Looping: 2
Looping: 2
Looping2: 2
As you see the first System.out.println is 2 times executed and the second only once. It happens because of
if(n%i == 0){
return false;
}
If n%i == 0 gives true then the method will return false and for loop stops executing. This explains why it makes difference where to put System.out.println.
More useful information you will get here.

Related

IndexOutOfRangeException: Can't figure out why index out of bound

So, I have a list of Upgrade systems for my game but it has a bug on it when I press upgrade for a second time the index out of range then pressed for the third times the index out of range gone. this whole script.
void Start()
{
newSelectedIndex = previousSelectedIndex = PlayerPrefs.GetInt("currentPlayer");
btn = Select_Player[newSelectedIndex].GetComponent<Button>();
btn.interactable = false;
Coins = M_CoinManager.instance.Coins;
for (int i = 0; i < Select_Player.Length; i++)
{
priceText[i].text = Cost_Player[i].ToString();
value_player[i] = "" + i;
Select_Player[i].SetActive(false);
buyPlayer[i] = PlayerPrefs.GetInt(value_player[i]);
}
//if(PlayerPrefs.HasKey("currentPlayer")){
selectedVehicleIndex = PlayerPrefs.GetInt("currentPlayer");
theVehicles[selectedVehicleIndex].SetActive(true);
VehicleInfo();
UpgradeButtonStatus();
}
// Update is called once per frame
void Update()
{
for (int i = 0; i < Select_Player.Length; i++)
{
buyPlayer[i] = PlayerPrefs.GetInt(value_player[i]);
if (i == buyPlayer[i])
{
Select_Player[i].SetActive(true);
upgradeBtn[i].interactable = true;
UpgradeButtonStatus();
}
else
{
upgradeBtn[i].interactable = false;
}
}
}
public void BuyCharact(int id)
{
M_SoundManager.instance.playUIsfx();
if (Cost_Player[id] <= Coins)
{
M_CoinManager.instance.AddCoins(-Cost_Player[id]);
PlayerPrefs.SetInt(value_player[id], id);
}
else
{
_CoinShake.DoShake();
Debug.Log("Does have enough coin");
}
}
public void Reset()
{
for (int i = 0; i < Select_Player.Length; i++)
{
PlayerPrefs.SetInt(value_player[i], 0);
}
}
public void Select(int id)
{
previousSelectedIndex = newSelectedIndex;
newSelectedIndex = id;
newSelectedIndex = selectedVehicleIndex;
PlayerPrefs.SetInt("currentPlayer", newSelectedIndex);
Button newbtn = Select_Player[previousSelectedIndex].GetComponent<Button>();
btn = Select_Player[newSelectedIndex].GetComponent<Button>();
btn.interactable = false;
newbtn.interactable = true;
M_SoundManager.instance.playUIsfx();
Debug.Log("Selected TypeCar" + newSelectedIndex);
}
public void nextVehicle()
{
M_SoundManager.instance.playUIsfx();
theVehicles[selectedVehicleIndex].SetActive(false);
selectedVehicleIndex = (selectedVehicleIndex + 1) % theVehicles.Length;
theVehicles[selectedVehicleIndex].SetActive(true);
VehicleInfo();
UpgradeButtonStatus();
}
public void PreviousVehicle()
{
M_SoundManager.instance.playUIsfx();
theVehicles[selectedVehicleIndex].SetActive(false);
selectedVehicleIndex--;
if (selectedVehicleIndex < 0)
{
selectedVehicleIndex += theVehicles.Length;
}
theVehicles[selectedVehicleIndex].SetActive(true);
VehicleInfo();
UpgradeButtonStatus();
}
public void VehicleInfo()
{
currLevel = _VehicleStats[0].carItem[selectedVehicleIndex].unlockedLevel;
levelText[selectedVehicleIndex].text = "Level: " + (currLevel + 1);
powerText[selectedVehicleIndex].text = "Power: " + _VehicleStats[0].carItem[selectedVehicleIndex].vehicleLevel[currLevel].motorPower;
brakeText[selectedVehicleIndex].text = "Brake: " + _VehicleStats[0].carItem[selectedVehicleIndex].vehicleLevel[currLevel].brakePower;
Debug.Log(selectedVehicleIndex);
}
public void upgradeMethod()
{
nextLevelIndex = _VehicleStats[0].carItem[selectedVehicleIndex].unlockedLevel + 1;
if (Coins >= _VehicleStats[0].carItem[selectedVehicleIndex].vehicleLevel[nextLevelIndex].unlockCost)
{
Coins -= _VehicleStats[0].carItem[selectedVehicleIndex].vehicleLevel[nextLevelIndex].unlockCost;
_VehicleStats[0].carItem[selectedVehicleIndex].unlockedLevel++;
if (_VehicleStats[0].carItem[selectedVehicleIndex].unlockedLevel < _VehicleStats[0].carItem[selectedVehicleIndex].vehicleLevel.Length - 1)
{
upgradeBtnText[selectedVehicleIndex].text = "Upgrade Cost :" + _VehicleStats[0].carItem[selectedVehicleIndex].vehicleLevel[nextLevelIndex + 1].unlockCost;
}
else
{
upgradeBtn[selectedVehicleIndex].interactable = false;
upgradeBtnText[selectedVehicleIndex].text = "Max Level";
}
VehicleInfo();
}
}
private void UpgradeButtonStatus()
{
if (_VehicleStats[0].carItem[selectedVehicleIndex].unlockedLevel < _VehicleStats[0].carItem[selectedVehicleIndex].vehicleLevel.Length - 1)
{
upgradeBtn[selectedVehicleIndex].interactable = true;
nextLevelIndex = _VehicleStats[0].carItem[selectedVehicleIndex].unlockedLevel + 1;
upgradeBtnText[selectedVehicleIndex].text = "Upgrade Cost :" + _VehicleStats[0].carItem[selectedVehicleIndex].vehicleLevel[nextLevelIndex + 1].unlockCost;
}
else
{
upgradeBtn[selectedVehicleIndex].interactable = false;
upgradeBtnText[selectedVehicleIndex].text = "Max Level";
}
}
and the error reference to this method :
private void UpgradeButtonStatus()
{
if (_VehicleStats[0].carItem[selectedVehicleIndex].unlockedLevel < _VehicleStats[0].carItem[selectedVehicleIndex].vehicleLevel.Length - 1)
{
upgradeBtn[selectedVehicleIndex].interactable = true;
nextLevelIndex = _VehicleStats[0].carItem[selectedVehicleIndex].unlockedLevel + 1;
upgradeBtnText[selectedVehicleIndex].text = "Upgrade Cost :" + _VehicleStats[0].carItem[selectedVehicleIndex].vehicleLevel[nextLevelIndex + 1].unlockCost;
}
else
{
upgradeBtn[selectedVehicleIndex].interactable = false;
upgradeBtnText[selectedVehicleIndex].text = "Max Level";
}
}
as you can see on the update that's what I mean. after i press upgrade for third times the error stopped.
and this for the inpector
Arrays length is one higher than their highest index, but last iteration of "for" loops goes to array.length.
You need to make "for" loops to array.length-1.
I see you do "for" loops of up to array.length.
I haven't truly read thru your whole script so there might be more, but it's a typical error in my "for" loops so I think that is causing your error.

C# for loop to print first 20 positive numbers divisible by 7?

This is Code I reached. What I don't understand is how do I put a condition to display the first 20 numbers where I wrote the condition for i to be less than 20. I know that my code is completely wrong.
for(int i=1; i<=20; i++)
{
if(i%7==0)
{
Console.WriteLine(i);
}
}
You're close. use a counter variable:
int counter = 0; // counter variable
for(int i=1; ; i++) // removed condition
{
if (counter > 20) break; // time to stop the iteration
if(i%7==0)
{
counter++;
Console.WriteLine(i);
}
}
This can be improved to:
for(int i = 7, counter = 0; counter <= 20; i += 7)
{
Console.WriteLine(i);
counter++;
}
The first 20 integers that are divisible by 7 are easily written as 7,2*7,3*7,4*7,...,20*7. This in your loop you can do:
for(int i = 1; i<=20; i++) {
Console.WriteLine(7*i);
}
Can’t you just go up in sevens?
for (int multiple = 7, int count = 0; count < 20; multiple += 7, count++)
{
Console.WriteLine(multiple);
}
You can try bellow code that will give you first 20 numbers that will covered the condition i%7==0 ........
public static void Main(string[] args)
{
int i=0, count = 0;
while(count < 20)
{
if (i % 7 == 0)
{
Console.WriteLine("Position {0} number is = {1}", count+1, i,"\n");
count++;
}
i++;
}
Console.ReadKey();
}

Eclipse: The selection cannot be launched, and there are no recent launches

So, I know that there are many people with this problem and many questions about it, but I just couldn't fin a solution for this, every other thing I try to execute works, but this doesn't and I can't figure out why...
package prob3;
public class LargestPrimeFactor {
double num = 600851475143D;
double LargestPrimeFactor;
public void getLargestPrimeFactor(String [] args){
double prevPrimeFactor = 0;
do {
for(double i = 0; i < num/2; i++){
if((num % i == 0) && (num / i != 1)){
prevPrimeFactor = num;
LargestPrimeFactor = num / i;
} else {
continue;
}
}
} while(prevPrimeFactor != LargestPrimeFactor);
System.out.println("The biggest prime factor of " + num + " is " + LargestPrimeFactor);
}
}
you should define a main function to run your program. Something like:
public static void main(String[] args) {
getLargestPrimeFactor(args);
}

While/if Loop is not working in class

I'm learning java and I'm having an issue with my if code not running.
In the following code I'm trying to determine if a number (variable num) is a triangle number (1,3, 6, 10 etc). The code should run through and give the "Is Triangle". However it keeps spitting out Null.
I understand this is not the most effective way to do this code, but I am trying to learn how to use Classes.
public class HelloWorld {
public static void main(String[] args) {
class NumberShape {
int num = 45;
int tri = 0;
int triplus = 0;
String triresult;
public String triangle() {
while (tri < num) {
if (tri == num) {
triresult = "Is a Triangle";
System.out.println("Is a Triangle");
} else if (tri + (triplus + 1) > num){
triresult = "Is Not a Triangle";
} else {
triplus++;
tri = tri + triplus;
}
}
return triresult;
}
}
NumberShape result = new NumberShape();
System.out.println(result.triangle());
}
}
Thanks for any help provided.
Try this code :
public class HelloWorld {
public static void main(String[] args) {
class NumberShape {
int num = 10;//Try other numbers
int tri = 0;
int triplus = 0;
int res = 0;
String triresult = "Is Not a Triangle";
int[] tab= new int[num];
public String triangle() {
//to calculate the triangle numbers
for(int i = 0; i<num; i++){
res = res + i;
tab[i]=res;
}
//To check if num is a triangle or not
for(int i = 0; i<tab.length; i++){
System.out.println(">> " + i + " : " + tab[i]);
if(tab[i]== num){
triresult = num + " Is a Triangle";
break;//Quit if the condition is checked
}else{
triresult = num + " Is Not a Triangle";
}
}
return triresult;
}
}
NumberShape result = new NumberShape();
System.out.println(result.triangle());
}
}
Hope this Helps.
Step through the loop carefully. You'll probably see that there is a case where
(tri < num)
fails, and thus you fall out of the loop, while
(tri == num)
and
(tri + (triplus + 1) > num)
both fail too, so no text gets set before you fall out.
You probably want to do your if-tests within the method on just tri, not a modification of tri, so as to reduce your own confusion about how the code is working.

issue in my if statement to make comparison in my java program

any help please, so i already wrote the prog but my if statement in my for loop is not working. the prog need to generate 6 random nos,then apply bubble sort which i already did.then the user must enter 6 numbers and these numbers must be compared against the random numbers and must say whether numbers are found in the random numbers or not. here's the code. something is wrong with the if statement ` public static void main(String[] args) {
try {
int numbers[] = new int[6]; //random numbers will be stored in new array
//2 loop will be created to avoid duplication of numbers
System.out.println("Array before Bubble sort");
for (int i = 0; i < 6; i++) {
numbers[i] = (int) (Math.random() * 40);
if (i > 0) {
for (int b = 0; b < i; b++) { //
if (numbers[b] == numbers[i]) {
i--; //decrement to continue the for loop if the integer has been repeated
}
}
}
System.out.print(numbers[i] + ","); //random numbers will be printed before using sorting bubble sort
}
//sort an array using bubble sort
bubbleSort(numbers);
System.out.println(" \nArray after bubble sort");
for (int i = 0; i < 6; i++) {
System.out.print(numbers[i] + ",");
}
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
System.out.println("\ninput 6 number between 1 and 40");
int inputNumber = Integer.parseInt(input.readLine());
for (int b = 0; b < 6; b++) {
System.out.println("number:");
int outcome=Integer.parseInt(input.readLine());
if(outcome==numbers){
System.out.println("found in random numbers");
}else{
System.out.println("not found in random numbers");
}
}
} catch (Exception e) {
System.out.println("error");
}
}
public static void bubbleSort(int[] numbers) {
int n = numbers.length;
int temp = 0;
for (int i = 0; i < n; i++) {
for (int j = 1; j < (n - i); j++) {
if (numbers[j - 1] > numbers[j]) { //swap the element
temp = numbers[j - 1];
numbers[j - 1] = numbers[j];
numbers[j] = temp;
}
}
}
}
}`
System.out.println("\ninput 6 number between 1 and 40");
//Scanner is specifically designed for getting an input purpose and introduced in Java 5,so better use it
Scanner s = new Scanner(System.in);
//you need to have nested loop here
//But the best way to search is use binary search,as you have already sorted the array
while (s.hasNextInt()) {
//one at a time from the input is put to outcome
int outcome = s.nextInt();
boolean found = false;
for (int b = 0; b < 6; b++) {
found = false;
if (outcome == numbers[b]) {
found = true;
//remember to break the inner loop if a match is found
break;
} else {
found = false;
}
}
if (found == true) {
System.out.println("found in random numbers");
} else {
System.out.println("not found in random numbers");
}