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

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();
}

Related

Implementation of Dijkstra’s mutual exclusion algorithm

I am trying to implement a Dijkstra's algorithm into a fork/join threadpool (consists the main threadpool with a global task queue and N threads with its own task queue) based on Dijkstra's Solution of a problem in concurrent programming control and Frigo's and Leiserson's and Randall's The implementation of the cilk-5 multithreaded language.
But, it seems too complicated. So, I used Filter Lock from Art of Multiprocessor Programming as following:
Book's implementation
class Filter implements Lock {
int[] level;
int[] victim;
public Filter(int n) {
level = new int[n];
victim = new int[n]; // use 1..n-1
for (int i = 0; i < n; i++) {
level[i] = 0;
}
}
public void lock() {
int me = ThreadID.get();
for (int i = 1; i < n; i++) { //attempt level 1
level[me] = i;
victim[i] = me;
// spin while conflicts exist
while ((∃k != me) (level[k] >= i && victim[i] == me)) {};
}
}
public void unlock() {
int me = ThreadID.get();
level[me] = 0;
}
}
My implementation in threadpool
static int* flag;
static int* victim;
const int MAX = 1e9;
int ans = 0;
int nthreads = 10;
struct pt
{
int id;
pthread_t thread;
};
static bool existK(int j, int i, int nthreads){
for (int k = 0; k < nthreads ; k++){
if (flag[k] >= j && k != i)
{
return true;
}
}
return false;
}
void lock_init(void)
{
flag = (int *) calloc(nthreads, sizeof(int));
victim = (int *) calloc(nthreads, sizeof(int));
}
// Executed before entering critical section
void lock(int i)
{
for (int j = 1; j < nthreads; j++){
flag[i] = j;
victim[j] = i;
while (existK(j, i, nthreads) && victim[j] == i);
}
}
// Executed after leaving critical section
void unlock(int i)
{
flag[i] = 0;
}
// in main()
void* func(void *pw)
{
while (true) {
lock(threadID);
// working on its own queue if there is a task and
// after it finishes this task, call unlock(threadID) and call continue;
//if the global queue has tasks left, work on it and call unlock and continue
//if the other worker queue has tasks left, work on it and call unlock and continue
}
}
// Driver code
int main()
{
struct pt** ptr;
lock_init();
ptr = ((struct pt **)malloc(sizeof(struct pt *) * nthreads));
for (int i = 0; i < nthreads; i++){
ptr[i] = malloc(sizeof(struct pt));
(ptr[i])->id = i;
pthread_create(&(ptr[i])->thread, NULL, func, ptr[i]);
}
for (int i = 0; i < nthreads; i++){
pthread_join((ptr[i])->thread, NULL);
}
return 0;
}
However, with my implementation, the main loop is much slower than just using the pthread_mutex_lock and pthread_mutex_unlock. I am not sure if I use the algorithm in a wrong place or my algorithm is wrong at this point.
Additionally, I am wondering how to stealing tasks to work on from the
other workers’ queues in an efficient way (locating the worker with available tasks)

Looping. Why is this happening? Prime 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.

Boolean class missing a return statement java

I want to check if the two arrays have the same elements, but it says missing return statement although I have returned as below. What's the problem?
My method can get correct value if I write in a void function.
public static boolean get(int[] One, int[] Two, int target) {
int [] temp = new int[One.length];
for (int i = 0 ; i < One.length; i ++){
temp[i] = target - One[i];
}
for (int m = 0; m < temp.length; m++){
for (int n = 0; n < Two.length; n ++){
if (temp[m]==Two[n]){
return true;
}
else return false;
}
}
}
The compiler won't accept it because it is possible to reach the end without ever returning anything. You can structure it like this so that no matter what the input is, it will always return true or false.
public static boolean get(int[] One, int[] Two, int target) {
int [] temp = new int[One.length];
for (int i = 0 ; i < One.length; i ++){
temp[i] = target - One[i];
}
for (int m = 0; m < temp.length; m++){
for (int n = 0; n < Two.length; n ++){
if (temp[m]==Two[n]){
return true;
}
else {
return false;
}
}
}
return false;
}
It's possible for the function to finish without returning if either temp.length or Two.length are 0.
i have no idea what you gonna do , but if you add a return false; into the last line of your method , it would work
public static boolean get(int[] One, int[] Two, int target) {
int [] temp = new int[One.length];
for (int i = 0 ; i < One.length; i ++)
temp[i] = target - One[i];
for (int m = 0; m < temp.length; m++){
for (int n = 0; n < Two.length; n ++){
if (temp[m]==Two[n]) return true;
else return false;
}
}
return false;
}
Think about what will happen if temp.length is 0 ...

Attempts to call a method in the same class not working (java)

I'm creating a random number generator which then sorts the digits from largest to smallest. Initially it worked but then I changed a few things. As far as I'm aware I undid all the changes (ctrl + z) but now I have errors at the points where i try to call the methods. This is probably a very amateur problem but I haven't found an answer. The error i'm met with is "method in class cannot be applied to given types"
Here's my code:
public class RandomMath {
public static void main(String[] args) {
String bigger = bigger(); /*ERROR HERE*/
System.out.println(bigger);
}
//create method for generating random numbers
public static int generator(int n){
Random randomGen = new Random();
//set max int to 10000 as generator works between 0 and n-1
for(int i=0; i<1; i++){
n = randomGen.nextInt(10000);
// exclude 1111, 2222, 3333, 4444, 5555, 6666, 7777, 8888, 9999, 0000
if((n==1111 || n==2222 || n==3333 || n ==4444 || n==5555)
||(n==6666 || n==7777 || n==8888 || n==9999 || n==0000)){
i--;
}
}
return n;
}
//create method for denoting the bigger number
public static String bigger(int generated){
generated = generator(); /*ERROR HERE*/
System.out.println(generated);
int[] times = new int[10];
while (generated != 0) {
int val = generated % 10;
times[val]++;
generated /= 10;
}
String bigger = "";
for (int i = 9; i >= 0; i--) {
for (int j = 0; j < times[i]; j++) {
bigger += i;
}
}
return bigger;
}
}
You have not defined a method bigger(), only bigger(int generated). Therefore, you must call your bigger method with an integer parameter.

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");
}