public String primeNumbers()
{
//create variable to be returned
String prime = "";
int num = 0;
for(int i = 0; i < this.limit; i++)
{
num = this.limit - i;
for(int count = 2; count < this.limit; count++)
{
if ( num % count == 0)
{
count = this.limit + 1;
}
else if ( num == count)
{
prime += num + ", ";
}
}
}
return prime;
}
The goal of this is to produce a list of prime numbers in between 1 and the upper limit which is the private variable limit. However, when I run the code, I get a blank message as a return. Why is this?
I don't quite understand the logic of your code, but having helper methods is good.
public String primeNumbers()
{
//create variable to be returned
String prime = "";
for(int i = 0; i < this.limit; i++)
{
if(this.isPrime(i)){
prime += i + ", ";
}
}
return prime;
}
private boolean isPrime(int number){
if(number <= 1){
return false;
} else if(number == 2){
return true;
}
for(int i = 2; i < number; i++){
if(number%i == 0){
return false;
}
}
return true;
}
The isPrime() is naive, and can definitely be optimized.
There was a question about this yesterday and I ended up writing this as a refresher for myself.
public class Erasthotenes
{
private int range;
private boolean[] nums;
public Erasthotenes(int range)
{
this.range = range;
nums = new boolean[range];
for(int i = 0; i < nums.length; ++i)
{
nums[i] = true;
}
nums[0] = nums[1] = false;
}
public void sieve()
{
int root = (int) Math.sqrt(range);
for(int i = 2; i < root; ++i)
{
for(int j = i + 1; j < range; ++j)
{
if(j % i == 0)
{
nums[j] = false;
}
}
}
}
public void printPrimes()
{
for(int i = 0; i < nums.length; ++i)
{
if(nums[i] == true)
{
System.out.print(i + ", ");
}
}
}
}
http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
Related
What I need it to do is print all of the prime numbers starting at 1 and ending at the input, if the input is also a prime number. Here's my code now:
static void primeNumbers(int n) {
boolean isPrime;
System.out.println("All the prime numbers up to " + n + " are -->");
for (int prime = 2; prime < n; prime = prime++) {
if (n % prime == 0) {
isPrime = false;
}
if(isPrime == true){
System.out.println(prime);
}
}
}
My teacher said that I need to make a nested for loop, but I just don't know what to put in it. I'm also getting an error saying that my last use of isPrime hasn't been initialized.
You need to actually check for primality, and not just see if the number is a factor of n:
static boolean isPrime(int n) {
if (n < 2) {
return false;
}
if (n % 2 == 0) {
return n == 2;
}
for (int k = 3; k * k <= n; k += 2) {
if (n % k == 0) {
return false;
}
}
return true;
}
static void primeNumber(int n) {
System.out.println("All the prime numbers up to " + n + " are -->");
for (int num = 2; num < n; num ++) {
if (isPrime(num)) {
System.out.println(num);
}
}
}
You will need to do something like this for your program to work.
static void primeNumbers(int n) {
boolean isPrime = true;
System.out.println("All the prime numbers up to " + n + " are -->");
for (int prime = 2; prime < n; prime++) {
if (n % prime == 0) {
isPrime = false;
}else{
isPrime = true;
}
if(isPrime){
System.out.println(prime);
}
}
}
It is necessary to initialize isPrime.
And, Eratosthenes' s sieve is famous algorithm for get prime numbers.
I think the URL below will help you.
https://www.geeksforgeeks.org/java-program-for-sieve-of-eratosthenes/
here is one of the solutions
public static void main(String[] args) {
int n = 23;
boolean[] isPrime = new boolean[n + 1];
for (int i = 1; i <= n; i++) {
isPrime[i] = true;
}
for (int i = 2; i <= n / i; i++) {
if (isPrime[i]) {
for (int j = i; j <= n / i; j++) {
isPrime[i * j] = false;
}
}
}
for (int i = 1; i <= n; i++) {
if (isPrime[i]) {
System.out.println(i);
}
}
}
My code doesn't work and i don't know either why or how to make it work. This is my code.
public static void ex5(){
Scanner scan = new Scanner(System.in);
int givenNr = scan.nextInt();
int m = 1;
for (int i = 2; i < givenNr; i++){
while (m <= i/2 ){
if(i % m != 0) {
System.out.print(i + " ");
}
m++;
}
}
}
public static void ex5() {
Scanner scan = new Scanner(System.in);
int givenNr = scan.nextInt();
for (int i = 2; i < givenNr; i++) {
if (isPrime(i))
System.out.println(i);
}
}
public static boolean isPrime(int n) {
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0)
return false;
}
return true;
}
I wrote the code in JAVA and it seems to work fine in Eclipse. But I get an error when I submite the code in SPOJ(runtime error (NZEC) ).
Could someone please help me with this.
Here what I tried so far:
class Main {
public static void main(String[] args) throws java.lang.Exception {
Scanner n1 = new Scanner(System.in);
Scanner n3 = new Scanner(System.in);
int n2 = n1.nextInt();
int[][] n4 = new int[n2][2];
for (int i = 0; i < n2; i++) {
String[] s2 = n3.nextLine().split(" ");
for (int j = 0; j < 2; j++) {
n4[i][j] = Integer.parseInt(s2[j]);
}
}
for (int i = 0; i < n2; i++){
for(int j=n4[i][0];j<=n4[i][1];j++){
if(isPrimeNumber(j)){
System.out.println(j);
}
}
System.out.println();
}
}
public static boolean isPrimeNumber(int number) {
if (number == 2 || number == 3) {
return true;
}
if (number % 2 == 0) {
return false;
}
int sqrt = (int) Math.sqrt(number) + 1;
for (int i = 3; i < sqrt; i += 2) {
if (number % i == 0) {
return false;
}
}
return true;
}
}
1st thing you need to do is use the scanner properly and get rid off the 2nd one..
you are using 2 scanners because only one is not working as expected, why?
because you forgot that the Scanner#nextInt method does not consume the last newline character of your input, and thus that newline is consumed in the next call to Scanner#nextLine
Try this:
public static void main(String[] args) throws ParseException {
Scanner input = new Scanner(System.in);
int n2 = input.nextInt();
input.nextLine();
int[][] n4 = new int[n2][2];
for (int i = 0; i < n2; i++) {
String string2 = input.nextLine();
String[] s2 = string2.split(" ");
for (int j = 0; j < 2; j++) {
n4[i][j] = Integer.parseInt(s2[j]);
}
}
for (int i = 0; i < n2; i++) {
for (int j = n4[i][0]; j <= n4[i][1]; j++) {
if (isPrimeNumber(j)) {
System.out.println(j);
}
}
System.out.println();
}
}
public static boolean isPrimeNumber(int number) {
if (number == 2 || number == 3) {
return true;
}
if (number % 2 == 0) {
return false;
}
int sqrt = (int) Math.sqrt(number) + 1;
for (int i = 3; i < sqrt; i += 2) {
if (number % i == 0) {
return false;
}
}
return true;
}
}
import java.util.Scanner;
public class Recursion
{
//variables to hold string values
public static String s1 = new String(new char[10]);
public static String s2 = new String(new char[10]);
public static String s3 = new String(new char[11]);
public static String charSet = new String(new char[11]);
//variables to hold number values
public static int numberOne;
public static int numberTwo;
public static int numberThree;
public static int maxCharCount;
public static int[] numberSet = new int[10];
//function which generates a number
public static void checkForEquality()
{
numberOne = numberTwo = numberThree = 0;
int i;
int j;
for (i = 0; i < s1.length(); i++)
{
for (j = 0; j < maxCharCount; j++)
{
if (s1.charAt(i) == charSet.charAt(j))
{
if (i == 0 && numberSet[j] == 0)
return;
//generate the number
numberOne = (numberOne * 10) + numberSet[j];
}
}
}
for (i = 0; i < s2.length(); i++)
{
for (j = 0; j < maxCharCount; j++)
{
if (s2.charAt(i) == charSet.charAt(j))
{
if (i == 0 && numberSet[j] == 0)
return;
//generate number
numberTwo = (numberTwo * 10) + numberSet[j];
}
}
}
for (i = 0; i < s3.length(); i++)
{
for (j = 0; j < maxCharCount; j++)
{
if (s3.charAt(i) == charSet.charAt(j))
{
if (i == 0 && numberSet[j] == 0)
return;
//generate the number
numberThree = (numberThree * 10) + numberSet[j];
}
}
}
}
public static void display(){
if (numberOne + numberTwo == numberThree) {
//display the output
int i=0;
System.out.println();
System.out.print(" Summation Puzzle solved. ");
System.out.print("n");
System.out.print(s1);
System.out.print("<==>");
System.out.print(numberOne);
System.out.print("n");
System.out.print(s2);
System.out.print("<==>");
System.out.print(numberTwo);
System.out.print("n");
System.out.print(s3);
System.out.print("<==>");
System.out.print(numberThree);
System.out.print("n");
//loop to show the result
for (i = 0; i < maxCharCount; i++)
{
System.out.println(charSet.charAt(i));
System.out.print("<==>");
System.out.print(numberSet[i]);
System.out.print("n");
}
System.exit(0);
}
}
//recursive function which will call itself
public static void Combinations(int indexCounter, int[] availableSet)
{
int i;
if (indexCounter != 0)
{
for (i = 0; i < 10; i++)
{
numberSet[indexCounter] = i;
if (availableSet[i] == 1)
{
availableSet[i] = 0;
Combinations(indexCounter + 1, availableSet);
availableSet[i] = 1;
}
}
}
if (indexCounter == maxCharCount)
checkForEquality();
}
public static void createCharSet()
{
int i;
int setIndex;
int present;
int j;
setIndex = 0;
for (i = 0; i < s1.length(); i++)
{
present = 0;
for (j = 0; j < setIndex; j++)
{
if (s1.charAt(i) == charSet.charAt(j))
{
present = 1;
}
}
if (present == 0)
{
charSet = StringFunctions.changeCharacter(charSet, setIndex++, s1.charAt(i));
}
}
for (i = 0; i < s2.length(); i++)
{
present = 0;
for (j = 0; j < setIndex; j++)
{
if (s2.charAt(i) == charSet.charAt(j))
{
present = 1;
}
}
if (present == 0)
{
charSet = StringFunctions.changeCharacter(charSet, setIndex++, s2.charAt(i));
}
}
for (i = 0; i < s3.length(); i++)
{
present = 0;
for (j = 0; j < setIndex; j++)
{
if (s3.charAt(i) == charSet.charAt(j))
{
present = 1;
}
}
if (present == 0)
{
charSet = StringFunctions.changeCharacter(charSet, setIndex++, s3.charAt(i));
}
}
maxCharCount = setIndex;
}
public static void calculateSummation()
{
int loop;
if (maxCharCount > 10)
{
System.out.print("Please check the input again");
return;
}
else
{
int[] avaliableSet = new int[10];
for (loop = 0; loop < 10; loop++)
{
avaliableSet[loop] = 1;
}
Combinations(0, avaliableSet);
}
}
//main method
public static void main(String[]args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter the first String :");
s1 = scan.next();
System.out.print("Enter the second String :");
s2 = scan.next();
System.out.print("Enter the thirsd String :");
s3 = scan.next();
createCharSet();
System.out.print(" result of your 3 three strings = ");
System.out.print(charSet);
calculateSummation();
checkForEquality();
display();
}
}
Every time I run the program it just assigns 0 to each value. I want to be able to assign a value from 1-10 to each non numeric character.
can someone help me out.?
it should look something like this
Sample output
First off, you may find debugging easier if you properly format your code. I remember you posting last night where you experienced similar issues resulting from syntax. You may find that your code is easier to read if you format it like this:
//function which generates a number
public static void checkForEquality(){
numberOne = numberTwo = numberThree = 0;
int i;
int j;
for (i = 0; i < s1.length(); i++){
for (j = 0; j < maxCharCount; j++){
if (s1.charAt(i) == charSet.charAt(j)){
if (i == 0 && numberSet[j] == 0)
return;
//generate the number
numberOne = (numberOne * 10) + numberSet[j];
}
}
}
for (i = 0; i < s2.length(); i++){
for (j = 0; j < maxCharCount; j++){
if (s2.charAt(i) == charSet.charAt(j)){
if (i == 0 && numberSet[j] == 0)
return;
//generate number
numberTwo = (numberTwo * 10) + numberSet[j];
}
}
}
Take a look at just this portion of your code and see if it still properly follows your algorithm. You may find an error which you could've located yourself with properly formatted code. If you take a look at a previous question of yours (which I answered) you'll find a helpful link that guides you to writing better code.
Also, I didn't try to compile this in my own IDE, but you should take a look at Eclipse. A lot of the small errors you're getting could be located automatically by Eclipse.
public class CreditCardNumber {
private String issuerID = "000000";
private String accountNum = "999999999";
private int checkDigit = 0;
public CreditCardNumber(String TempissuerID, String TempaccountNum) {
if (TempissuerID != null && TempaccountNum != null
&& TempissuerID.length() == 6 && TempaccountNum.length() == 9)
if (Digits(TempissuerID) && Digits(TempaccountNum)) {
issuerID = TempissuerID;
accountNum = TempaccountNum;
calcCheckDigits();
}
}
public boolean Digits(String temp1) {
String temp = "0123456789";
int count = 0;
for (int i = 0; i < temp1.length(); i++)
for (int j = 0; j < temp.length(); j++)
if (temp1.charAt(i) == temp.charAt(j)) {
count++;
}
if (count == temp1.length()) {
return true;
}
return false;
}
public CreditCardNumber() {
}
public String getID() {
return issuerID;
}
public String getAccNum() {
return accountNum;
}
public int getDigits() {
return checkDigit;
}
private void calcCheckDigits() {
int sum;
sum = checkSum();
if ((sum + checkDigit) % 10 != 0) {
checkDigit = sum - (sum % 10);
}
System.out.printf("%d", checkDigit);
}
public void CreateCred(String TempissuerID) {
if (TempissuerID != null && TempissuerID.length() == 6
&& Digits(TempissuerID)) {
issuerID = TempissuerID;
} else {
issuerID = "000000";
}
StringBuilder TempString = new StringBuilder();
for (int i = 0; i < 9; i++) {
TempString = TempString.append((Math.random() * (9 - 0 + 1) + 0));
}
accountNum = TempString.toString();
calcCheckDigits();
}
private int checkSum() {
StringBuilder temp = new StringBuilder();
int num;
int sum = 0;
for(int i = 0 ; i <issuerID.length();i++)
{
temp = temp.append(issuerID.charAt(i));
}
for(int j = 0 ; j < accountNum.length(); j++)
{
temp = temp.append(accountNum.charAt(j));
}
System.out.println(temp);
for (int k = 0; k < temp.length(); k += 2) {
num = temp.charAt(k) - '0';
num *= 2;
if (num > 9)
num = 1 + (num % 10);
temp.setCharAt(k, (char) num);
}
for (int v = 0; v < temp.length(); v++) {
sum += temp.charAt(v) - '0';
}
System.out.printf("%d", sum);
return sum;
}
public String toString() {
String s = "";
String str = issuerID + accountNum;
return str;
}
}
I have a problem in my checksum method, I wrote some printf statement to check for the value of sum which turn out to be -930 but This is not what the value sum suppose to be , if adding only there is no reason for it to have a negative sign.I am expecting the checkDigit number to be 9 when I enter 321321 for issuerID and 654654654 for accountNum, and the value of sum in check sum will be passed to the calCheckDigits method to get the value for CheckDigit which is 9.
What am I doing wrong in this method?
ok I just edit the code now I get -30 for the sum
I just edit again my first 2 for loops in checksum was wrong leading my temp string value to be incorrect
now it get -320
still incorrect but getting better